PHP

Deep Merge Associative PHP Arrays Recursively

Learn to deeply merge multiple associative PHP arrays, combining nested arrays and overriding scalar values, perfect for complex configuration management.

<?php
/**
 * Recursively merges two or more arrays.
 * Unlike array_merge_recursive, this function overwrites scalar values
 * instead of creating a new array when keys match.
 *
 * @param array $array1 The first array to merge.
 * @param array $array2 The second array to merge.
 * @return array The merged array.
 */
function array_deep_merge(...$arrays) {
    $merged = [];
    foreach ($arrays as $array) {
        foreach ($array as $key => $value) {
            if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
                $merged[$key] = array_deep_merge($merged[$key], $value);
            } else {
                $merged[$key] = $value;
            }
        }
    }
    return $merged;
}

$config1 = [
    'database' => [
        'host' => 'localhost',
        'user' => 'root'
    ],
    'app' => [
        'name' => 'MyApp',
        'debug' => true
    ]
];

$config2 = [
    'database' => [
        'user' => 'admin',
        'password' => 'secret'
    ],
    'app' => [
        'debug' => false,
        'version' => '1.0'
    ],
    'cache' => [
        'enabled' => true
    ]
];

$mergedConfig = array_deep_merge($config1, $config2);

/*
Expected output for $mergedConfig:
[
    "database" => [
        "host" => "localhost",
        "user" => "admin",
        "password" => "secret",
    ],
    "app" => [
        "name" => "MyApp",
        "debug" => false,
        "version" => "1.0",
    ],
    "cache" => [
        "enabled" => true,
    ],
]
*/
print_r($mergedConfig);
?>
How it works: This function `array_deep_merge` provides a robust way to combine multiple associative arrays recursively. Unlike PHP's built-in `array_merge_recursive` which creates new arrays for matching keys, this custom function smartly overwrites scalar values and deep-merges only when both corresponding values are arrays. This makes it ideal for managing layered configurations where later arrays should override earlier ones while preserving nested structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs