PHP

Deep Merge Associative Arrays

Learn to recursively merge two or more associative arrays in PHP, correctly handling nested arrays and overwriting scalar values in a flexible manner.

<?php

function array_deep_merge(...$arrays): array
{
    $result = array_shift($arrays); // Start with the first array

    foreach ($arrays as $array) {
        foreach ($array as $key => $value) {
            if (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
                // Both current and new values are arrays, recurse
                $result[$key] = array_deep_merge($result[$key], $value);
            } else {
                // New value overwrites current value (scalar or if types don't match)
                $result[$key] = $value;
            }
        }
    }

    return $result;
}

$array1 = [
    'a' => 1,
    'b' => [
        'b1' => 'val1',
        'b2' => 'val2'
    ],
    'c' => 3,
    'nested' => [
        'x' => 10,
        'y' => 20
    ]
];

$array2 = [
    'b' => [
        'b2' => 'new_val2',
        'b3' => 'val3'
    ],
    'd' => 4,
    'nested' => [
        'y' => 25,
        'z' => 30
    ]
];

$array3 = [
    'a' => 'new_a',
    'e' => 5
];

$merged = array_deep_merge($array1, $array2, $array3);

echo "Original Array 1:
";
print_r($array1);

echo "
Original Array 2:
";
print_r($array2);

echo "
Original Array 3:
";
print_r($array3);

echo "
Deep Merged Array:
";
print_r($merged);

?>
How it works: The `array_merge()` function in PHP does a shallow merge, meaning it replaces entire sub-arrays rather than merging them recursively. This `array_deep_merge` function provides a solution for merging any number of associative arrays recursively. It takes a variable number of arrays using `...$arrays`. It starts with the first array as the base and then iterates through subsequent arrays. For each key, if both the existing value and the new value are arrays, it recursively calls `array_deep_merge` for that nested structure. Otherwise, the new value overwrites the existing one. This ensures that nested associative arrays are merged correctly, preserving all data while updating common keys.

Need help integrating this into your project?

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

Hire DigitalCodeLabs