The array_diff_assoc() function compares arrays and returns the entries from the first array that are not present in the other arrays. It compares both the key and value when checking for a match.
Version Support: array_diff_assoc() in PHP 8.5, array_diff_assoc() in PHP 8.4, array_diff_assoc() in PHP 8.3, array_diff_assoc() in PHP 8.2, array_diff_assoc() in PHP 8.1, array_diff_assoc() in PHP 7.1, array_diff_assoc() in PHP 7.2, array_diff_assoc() in PHP 7.3, array_diff_assoc() in PHP 7.4
Syntax
array_diff_assoc(array $array, array ...$arrays): array
- $array: The array to compare.
- $arrays: One or more arrays to compare against.
- Returns: An array containing entries from the first array that have no matching key-value pair in the other arrays. Original keys are preserved.
Example
<?php
$array1 = [ "a" => "apple", "b" => "banana", "c" => "cherry" ];
$array2 = [ "a" => "apple", "b" => "blueberry", "d" => "date" ];
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
Output:
Array
(
[b] => banana
[c] => cherry
)
The "a" => "apple" entry is excluded because both its key and value match in $array2. The "b" => "banana" entry remains because the key matches, but the value does not.
How It Differs from array_diff()
array_diff() compares values only, while array_diff_assoc()compares both keys and values.
<?php
$array1 = ["color" => "blue"];
$array2 = ["shade" => "blue"];
print_r(array_diff($array1, $array2)); // No differences
print_r(array_diff_assoc($array1, $array2)); // ["color" => "blue"]
The value is the same, but the key differs, so array_diff_assoc()treats the entry as unique to $array1.
Comparing More Than Two Arrays
You can pass multiple arrays. An entry is returned only if its key-value pair is absent from all the other arrays:
$result = array_diff_assoc($array1, $array2, $array3);