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 tow 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.


Example:

In the following example, you can see – All the three arrays have red, green, and blue, but yellow is only in the first array, So it will return yellow.

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

<?php
$array1 =array("red", "green", "blue","yellow");
$array2 =array("red", "green", "oragens", "Purpel");
$array3 =array("red", "green", "blue");

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

echo "<pre>";
var_dump($result);
echo "</pre>";
?>
Browser Output
array(1) {
  [3]=>
  string(6) "yellow"
}

Leave a Reply

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