PHP

Deep Merging Multiple Associative Arrays

Discover how to deeply merge multiple associative arrays in PHP, ideal for combining configuration settings or default options while preserving nested structures.

<?php
function array_merge_recursive_distinct(array &array1, array &array2) {
    $merged = $array1;
    foreach ($array2 as $key => &$value) {
        if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
            $merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
        } else {
            $merged[$key] = $value;
        }
    }
    return $merged;
}

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

$config2 = [
    'database' => [
        'password' => 'secret',
        'port' => 3306
    ],
    'app' => [
        'env' => 'production'
    ],
    'logging' => [
        'level' => 'info'
    ]
];

$mergedConfig = array_merge_recursive_distinct($config1, $config2);
print_r($mergedConfig);
?>
How it works: The custom `array_merge_recursive_distinct` function provides a way to recursively merge associative arrays. Unlike PHP's built-in `array_merge_recursive`, this version will overwrite scalar values in the first array with those from the second array rather than appending them, which is often the desired behavior for configuration or default options. It iterates through the second array, recursively merging nested arrays and overwriting non-array values at corresponding keys.

Need help integrating this into your project?

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

Hire DigitalCodeLabs