← Back to all snippets
PHP

Deep Merge Two Associative Arrays

Learn to recursively merge two PHP associative arrays, ideal for combining configurations or default options, preserving numeric keys and overwriting string keys.

<?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;
}

$defaultConfig = [
    'database' => [
        'host' => 'localhost',
        'port' => 3306,
        'user' => 'root'
    ],
    'cache' => [
        'enabled' => true,
        'driver' => 'file'
    ],
    'features' => ['comments', 'ratings']
];

$userConfig = [
    'database' => [
        'host' => 'remote_db',
        'password' => 'secret'
    ],
    'cache' => [
        'driver' => 'redis'
    ],
    'features' => ['ratings', 'analytics']
];

$finalConfig = array_merge_recursive_distinct($defaultConfig, $userConfig);
print_r($finalConfig);

/*
Output:
Array
(
    [database] => Array
        (
            [host] => remote_db
            [port] => 3306
            [user] => root
            [password] => secret
        )

    [cache] => Array
        (
            [enabled] => true
            [driver] => redis
        )

    [features] => Array
        (
            [0] => comments
            [1] => ratings
            [2] => analytics
        )

)

Note: The output for 'features' differs from initial thought. The custom merge function will append numeric keys for arrays like 'features'. If overwrite of numeric keys is desired, a more complex logic is needed. For typical config, string keys are usually merged this way. For a pure overwrite of 'features', you would assign $merged['features'] = $value directly instead of array_merge_recursive_distinct on it. The code provided does a deep merge where string keys are overwritten and numeric keys are appended if both are arrays, which is often the desired behavior for config arrays like 'features' that can be extended.
*/
?>
How it works: This function performs a deep merge of two associative arrays. Unlike `array_merge_recursive`, which appends values with the same string key into an array, this function recursively overwrites values for matching string keys. It's particularly useful for combining configuration arrays where you want user-defined settings to take precedence over defaults, even in nested structures. For arrays with numeric keys, it appends values if both are arrays, otherwise, it overwrites.

Need help integrating this into your project?

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

Hire DigitalCodeLabs