PHP

Recursively Merge PHP Associative Arrays with Overwrite

Merge PHP associative arrays recursively, prioritizing values from later arrays. Ideal for deep merging configuration settings or data structures in your applications.

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

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

$config2 = [
    'database' => [
        'port' => 8889, // Overwrites 3306
        'password' => 'newpass'
    ],
    'app' => [
        'debug' => false, // Overwrites true
        'environment' => 'development'
    ],
    'cache' => [
        'driver' => 'file'
    ]
];

$mergedConfig = array_merge_recursive_distinct($config1, $config2);
/*
$mergedConfig will be:
[
    'database' => [
        'host' => 'localhost',
        'port' => 8889,
        'user' => 'root',
        'password' => 'newpass'
    ],
    'app' => [
        'name' => 'MyApp',
        'debug' => false,
        'environment' => 'development'
    ],
    'cache' => [
        'driver' => 'file'
    ]
]
*/
print_r($mergedConfig);
?>
How it works: This custom `array_merge_recursive_distinct` function merges two associative arrays recursively. Unlike `array_merge_recursive`, which appends values for same keys, this function overwrites existing scalar values and recursively merges sub-arrays, giving precedence to values from the second array. This is 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