PHP
Recursively Find Differences Between Two Associative Arrays
Discover how to recursively compare two associative arrays in PHP to identify differences in their values, including new, modified, or missing keys within nested structures.
<?php
function array_diff_recursive(array $array1, array $array2): array {
$diff = [];
foreach ($array1 as $key => $value) {
if (!array_key_exists($key, $array2)) {
$diff[$key] = $value; // Key exists in array1 but not in array2
} elseif (is_array($value) && is_array($array2[$key])) {
$subDiff = array_diff_recursive($value, $array2[$key]);
if (!empty($subDiff)) {
$diff[$key] = $subDiff; // Recursive difference
}
} elseif ($value !== $array2[$key]) {
$diff[$key] = $value; // Value is different
}
}
return $diff;
}
$oldSettings = [
'general' => [
'name' => 'Old App',
'version' => '1.0',
'enabled' => true,
'features' => ['A', 'B']
],
'database' => [
'host' => 'localhost',
'port' => 3306
]
];
$newSettings = [
'general' => [
'name' => 'New App', // Changed
'version' => '1.0',
'features' => ['A', 'C'] // Changed, 'B' removed, 'C' added
],
'database' => [
'host' => '127.0.0.1' // Changed
],
'logging' => [ // New section
'level' => 'info'
]
];
// Find what's in $oldSettings that's different or missing in $newSettings
$changesFromOldToNew = array_diff_recursive($oldSettings, $newSettings);
// Expected Output:
// Array
// (
// [general] => Array
// (
// [name] => Old App
// [features] => Array
// (
// [0] => A
// [1] => B
// )
// )
// [database] => Array
// (
// [host] => localhost
// )
// )
print_r($changesFromOldToNew);
// Note: This specific `array_diff_recursive` only shows elements that are in $array1
// but not in $array2, or are different. To show additions in $array2, you'd
// need to run it in reverse or combine with a check for new keys.
?>
How it works: The `array_diff_recursive` function compares two associative arrays deeply. It identifies keys present in the first array (`$array1`) but missing from the second (`$array2`), or keys whose scalar values differ. For nested arrays, it recursively calls itself to find differences, returning a structure mirroring `$array1` showing only the differing or missing parts. This is highly useful for comparing configurations or detecting modifications between complex data structures.