PHP

Recursively Merge Associative Arrays in PHP

Learn how to deep merge two or more associative arrays in PHP, ensuring nested arrays are properly combined and overwriting scalar values.

<?php
function array_merge_recursive_distinct(array &$array1, array &$array2): array
{
    $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;
}

$array1 = [
    'config' => [
        'host' => 'localhost',
        'port' => 80,
        'settings' => [
            'debug' => true,
            'log_level' => 'info'
        ]
    ],
    'version' => 1.0,
    'features' => ['auth', 'payments']
];

$array2 = [
    'config' => [
        'port' => 443,
        'settings' => [
            'log_level' => 'debug',
            'cache' => true
        ]
    ],
    'version' => 1.1,
    'features' => ['admin', 'api']
];

$mergedArray = array_merge_recursive_distinct($array1, $array2);
print_r($mergedArray);

/*
Expected Output:
Array
(
    [config] => Array
        (
            [host] => localhost
            [port] => 443
            [settings] => Array
                (
                    [debug] => 1
                    [log_level] => debug
                    [cache] => 1
                )
        )
    [version] => 1.1
    [features] => Array
        (
            [0] => auth
            [1] => payments
            [2] => admin
            [3] => api
        )
)
*/
?>
How it works: This function performs a recursive merge of two associative arrays. Unlike PHP's built-in `array_merge_recursive`, which appends values for identical keys, this custom function correctly overwrites scalar values and deeply merges nested arrays. It's ideal for merging configuration files or extending default settings.

Need help integrating this into your project?

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

Hire DigitalCodeLabs