PHP

Deep Merge Associative Arrays with Custom Overwrite

Master combining multiple associative arrays recursively, ensuring proper handling of nested structures and defining how duplicate keys are merged or overwritten.

<?php
function array_deep_merge_recursive(array ...$arrays): array {
    $result = [];
    foreach ($arrays as $array) {
        foreach ($array as $key => $value) {
            if (is_array($value) && isset($result[$key]) && is_array($result[$key])) {
                $result[$key] = array_deep_merge_recursive($result[$key], $value);
            } else {
                $result[$key] = $value;
            }
        }
    }
    return $result;
}

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

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

$mergedConfig = array_deep_merge_recursive($config1, $config2);
// var_dump($mergedConfig);
/* Expected Output (simplified):
[
    "database" => [
        "host" => "localhost",
        "user" => "admin", // Overwritten
        "port" => 3306,
        "password" => "secret" // Added
    ],
    "app" => [
        "name" => "MyApp",
        "debug" => false, // Overwritten
        "log_level" => "info" // Added
    ],
    "cache" => [
        "enabled" => true // Added
    ]
]
*/
?>
How it works: This `array_deep_merge_recursive` function allows you to combine an arbitrary number of associative arrays, handling nested arrays by recursively merging them. If a key exists in multiple arrays, the value from the later array in the arguments list will overwrite the earlier one. This is particularly useful for configuration files where you want to apply defaults and then override specific settings.

Need help integrating this into your project?

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

Hire DigitalCodeLabs