← Back to all snippets
PHP

Compare Two Associative Arrays to Find Differences

Discover how to find key-value differences between two associative arrays in PHP, identifying elements that are present in one but not the other, or have different values, even recursively for nested arrays.

<?php
function getArrayDiffAssocRecursive(array $array1, array $array2): array
{
    $difference = [];
    foreach ($array1 as $key => $value) {
        if (!array_key_exists($key, $array2)) {
            $difference[$key] = $value; // Key exists in array1 but not array2
        } elseif (is_array($value) && is_array($array2[$key])) {
            $recursiveDiff = getArrayDiffAssocRecursive($value, $array2[$key]);
            if (!empty($recursiveDiff)) {
                $difference[$key] = $recursiveDiff;
            }
        } elseif ($value !== $array2[$key]) {
            $difference[$key] = $value; // Value is different
        }
    }
    return $difference;
}

$configA = [
    'database' => [
        'host' => 'localhost',
        'user' => 'root',
        'password' => 'pass',
        'port' => 3306
    ],
    'app_name' => 'MyApp',
    'debug' => true,
    'features' => ['search', 'notifications']
];

$configB = [
    'database' => [
        'host' => 'remotehost', // Different
        'user' => 'admin',     // Different
        'password' => 'newpass',
    ],
    'app_name' => 'MyApp',
    'debug' => false, // Different
    'timeout' => 30, // New key in B (will appear in B vs A diff)
    'features' => ['search', 'auth'] // Different
];

echo "Differences in ConfigA compared to ConfigB:
";
print_r(getArrayDiffAssocRecursive($configA, $configB));

echo "
Differences in ConfigB compared to ConfigA:
";
print_r(getArrayDiffAssocRecursive($configB, $configA));
?>
How it works: This snippet provides a recursive function `getArrayDiffAssocRecursive` to find differences between two associative arrays, including nested arrays. It identifies keys present in the first array but not the second, or keys present in both but with differing values. This is crucial for comparing configurations, user preferences, or any data structures where you need to track changes across versions or sources, going beyond the single-level comparison of `array_diff_assoc`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs