PHP array_diff() function

PHP array_count_values() function
PHP array_diff_assoc() function

In PHP, the array diff() method compares the contents of two or more arrays and produces an array containing the values from the first array that are not present in any of the other arrays. It can be used to quickly find the difference between two or more arrays.

What is the syntax of the array_diff() function in PHP?

array array_diff ( array $array1 , array $array2 [, array $... ] )
ParametersDetails
array1The first array to compare with other arrays – required
array2Second array to make a comparison against- required
array3, ...Further arrays to compare against – optional

It takes at least two arrays as arguments, and compares the values of all arrays passed as arguments, it returns an array containing the values from the first array ($array1) that are not present in any of the other arrays ($array2, …)

Examples

Example 1.

The following code will return an array containing the values from $array1 that are not present in $array2:

$array1 = array(1, 2, 3, 4);
$array2 = array(3, 4, 5, 6);
$diff = array_diff($array1, $array2);
print_r($diff);

This would output:

Array
(
    [0] => 1
    [1] => 2
)

As you can see, the output is an array containing the values that were not included in $array2.
If you compare more than two arrays, it will return the values that are not present in all of them.

e.g:

$array1 = array(1, 2, 3, 4);
$array2 = array(3, 4, 5, 6);
$array3 = array(5,6,7,8);
$diff = array_diff($array1, $array2, $array3);
print_r($diff);

This would output:

Array
(
    [0] => 1
    [1] => 2
)

As you can see, this method produces an array containing all of the values from the first array that aren’t in the other arrays.

PHP array_count_values() function
PHP array_diff_assoc() function
en English
X
Scroll to Top