How to Compare Values of Arrays using PHP array_diff() Function

PHP array_diff() Function

The PHP array_diff() function is used to compare values of two or more arrays.

This array_diff() function returns an array that contains unmatched values ​​(those values ​​that are not in other arrays) of the first array.

Syntax of Array Diff function

array_diff($array1, $array2, $array3, ...);

This function takes at least two parameters, and all the parameters must be array types.


In the following example, you can see –

The first array has 5 color “red”, “green”, “blue”,”yellow”, and “Orange”

In the other array contains “red”, “green”, “blue”,”yellow” except “Orange”. So unmatched value is orange that’s why it will return Orange.

The array_diff() function compares the first array to other arrays. And it does not compare the keys to arrays, it compares only values.

$array1 =array("red", "green", "blue","yellow","Orange");
$array2 =array("red", "green");
$array3 =array("blue","yellow");

$result=array_diff($array1, $array2, $array3);

echo "<pre>";
echo "</pre>";
Browser Output
array(1) {
  string(6) "Orange"

Leave a Reply

Your email address will not be published. Required fields are marked *