PHP
Find Deep Differences Between Two Associative PHP Arrays
Recursively compare two associative arrays to identify added, removed, or modified key-value pairs, crucial for configuration or data synchronization.
function array_deep_diff(array $array1, array $array2): array
{
$diff = [];
// Check for removed keys from array1
foreach ($array1 as $key => $value) {
if (!array_key_exists($key, $array2)) {
$diff['removed'][$key] = $value;
}
}
// Check for added or modified keys in array2
foreach ($array2 as $key => $value) {
if (!array_key_exists($key, $array1)) {
$diff['added'][$key] = $value;
} elseif (is_array($value) && is_array($array1[$key])) {
$subDiff = array_deep_diff($array1[$key], $value);
if (!empty($subDiff)) {
$diff['modified'][$key] = $subDiff;
}
} elseif ($value !== $array1[$key]) {
$diff['modified'][$key] = [
'old' => $array1[$key],
'new' => $value
];
}
}
return $diff;
}
$originalConfig = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'password' => 'old_pass',
'options' => ['charset' => 'utf8']
],
'app_name' => 'MyApp',
'debug_mode' => true,
'features' => ['login', 'register', 'dashboard']
];
$newConfig = [
'database' => [
'host' => '127.0.0.1', // Changed
'port' => 3306,
'user' => 'admin', // Changed
'password' => 'new_pass', // Changed
'timeout' => 5 // Added
],
'app_name' => 'MyNewApp', // Changed
// 'debug_mode' removed
'environment' => 'production', // Added
'features' => ['login', 'dashboard', 'settings'] // 'register' removed, 'settings' added
];
$configDiff = array_deep_diff($originalConfig, $newConfig);
print_r($configDiff);
How it works: This recursive function compares two associative arrays to find deep differences. It identifies keys present only in the first array ('removed'), keys present only in the second array ('added'), and keys whose values have changed or are arrays that contain further differences ('modified'). For nested arrays, it recursively calls itself to find sub-differences.