← Back to all snippets
PHP

Deep Merge Associative Arrays Recursively

Learn how to recursively merge two or more associative arrays in PHP, handling nested structures without array_merge_recursive's default behavior for duplicate keys.

<?php
function arrayDeepMerge(array ...$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)) {
                $result[$key] = arrayDeepMerge($result[$key], $value);
            } else {
                $result[$key] = $value;
            }
        }
    }
    return $result;
}

$array1 = ['a' => 1, 'b' => ['x' => 10, 'y' => 20], 'c' => 3];
$array2 = ['b' => ['y' => 25, 'z' => 30], 'd' => 4];
$array3 = ['a' => 5, 'b' => ['x' => 100]];

$mergedArray = arrayDeepMerge($array1, $array2, $array3);
/*
Output:
Array
(
    [a] => 5
    [b] => Array
        (
            [x] => 100
            [y] => 25
            [z] => 30
        )

    [c] => 3
    [d] => 4
)
*/
print_r($mergedArray);
?>
How it works: This snippet provides a custom `arrayDeepMerge` function for recursively merging associative arrays. Unlike `array_merge_recursive`, which nests arrays when keys conflict, this function intelligently overwrites scalar values and recursively merges sub-arrays, ensuring the deepest values from subsequent arrays take precedence. It's ideal for merging configuration files or complex data structures where nested array values need to be combined rather than replaced or nested.

Need help integrating this into your project?

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

Hire DigitalCodeLabs