array_diff() Function Use in PHP

The array_diff() function compares arrays and returns the values from the first array that are not present in any of the other arrays.

Version Support: array_diff() in PHP 8.5, array_diff() in PHP 8.4, array_diff() in PHP 8.3, array_diff() in PHP 8.2, array_diff() in PHP 8.1, array_diff() in PHP 7.1, array_diff() in PHP 7.2, array_diff() in PHP 7.3, array_diff() in PHP 7.4

Syntax

array_diff(array $array, array ...$arrays): array

→The first array is the one being compared.
→Additional arrays contain values to check against.
→The result preserves the keys from the first array.

Example

<?php

$first = ["apple", "banana", "orange"];
$second = ["banana", "grape"];

$result = array_diff($first, $second);

print_r($result);

?>

Output:

Array
(
   [0] => apple
   [2] => orange
)

banana is excluded because it appears in $second. The original keys, 0 and 2, are preserved.

Comparing Multiple Arrays

<?php 

$a = [10, 20, 30, 40];
$b = [20, 50];
$c = [40];

$result = array_diff($a, $b, $c);

print_r($result);

?>

Output:

Array
(
   [0] => 10
   [2] => 30
)

6 Views