PHP
Find Differences (Keys & Values) Between Two Associative Arrays
Discover how to compare two associative arrays in PHP and identify all differences, including both differing keys and values, using `array_diff_assoc`.
<?php
$array1 = ['id' => 1, 'name' => 'Alice', 'city' => 'NY'];
$array2 = ['id' => 1, 'name' => 'Bob', 'city' => 'NY', 'age' => 30];
// Elements in $array1 that are not in $array2 (key AND value must match)
$diff_from_array1 = array_diff_assoc($array1, $array2);
/*
$diff_from_array1 will be:
[
'name' => 'Alice' // Because 'name' in $array2 is 'Bob'
]
*/
// Elements in $array2 that are not in $array1 (key AND value must match)
$diff_from_array2 = array_diff_assoc($array2, $array1);
/*
$diff_from_array2 will be:
[
'name' => 'Bob', // Because 'name' in $array1 is 'Alice'
'age' => 30 // Because 'age' does not exist in $array1
]
*/
?>
How it works: The `array_diff_assoc()` function compares two (or more) arrays and returns the values from the first array that are not present in the subsequent arrays, considering both keys and values. This is useful for identifying specific changes or unique entries between two associative arrays.