PHP array_diff_assoc() Function

With the PHP array_diff() function we can compare only values of arrays, but Using the PHP array_diff_assoc() function we can compare both values and keys of arrays.


Syntax of array_diff_assoc()

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

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


Example:

In the following example, you can see –

The first array has three colors “red”, “green”, and “blue”.

The other array contains “green”, and “blue” colors with the exact keys.

In the second array, the red color exists but the key is different that’s why it will return red.

The array_diff_assoc() function compares the first array to other arrays.

<?php
$array1 = array('x' => 'red', 'y' => 'green', 'z' => 'blue');
$array2 = array('a' => 'red', 'y' => 'green');
$array3 = array('z' => 'blue');

$result = array_diff_assoc($array1,$array2,$array3);
echo "<pre>";
var_dump($result);
echo "</pre>";
?>
Browser Output
array(1) {
  ["x"]=>
  string(3) "red"
}

Leave a Reply

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