PHP

Recursively Merge Multiple PHP Arrays Without Overwriting Numeric Keys

Implement a robust function to deep merge any number of PHP arrays, ensuring nested structures and numeric keys are handled correctly.

<?php
function array_merge_deep(array ...$arrays): array {
    $result = array_shift($arrays); // Start with the first array
    foreach ($arrays as $array) {
        foreach ($array as $key => $value) {
            if (is_array($value) && isset($result[$key]) && is_array($result[$key])) {
                $result[$key] = array_merge_deep($result[$key], $value);
            } elseif (is_numeric($key)) { // For numeric keys, append rather than overwrite
                $result[] = $value;
            } else {
                $result[$key] = $value;
            }
        }
    }
    return $result;
}

$arr1 = ['a' => 1, 'b' => ['x' => 10, 'y' => 20], 'c' => [1, 2]];
$arr2 = ['b' => ['y' => 25, 'z' => 30], 'd' => 4, 'c' => [3, 4]];
$arr3 = ['e' => 5, 'b' => ['w' => 50]];

$merged = array_merge_deep($arr1, $arr2, $arr3);
print_r($merged);
/*
Output will be:
Array
(
    [a] => 1
    [b] => Array
        (
            [x] => 10
            [y] => 25
            [z] => 30
            [w] => 50
        )

    [c] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

    [d] => 4
    [e] => 5
)
*/
?>
How it works: This custom function `array_merge_deep` recursively merges multiple arrays, providing more sophisticated control than PHP's native `array_merge_recursive`. It handles associative keys by overwriting earlier values with later ones, but crucially, it appends values for numeric keys to prevent overwriting. This ensures that nested arrays are merged properly, and lists (arrays with numeric keys) grow without losing elements from earlier arrays.

Need help integrating this into your project?

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

Hire DigitalCodeLabs