PHP

Recursively Merging Associative PHP Arrays

Implement a robust function to deeply merge multiple associative arrays, intelligently combining nested data structures without overwriting entire sub-arrays.

<?php
function array_merge_recursive_distinct(array ...$arrays): array {
    $merged = array_shift($arrays); // Start with the first array
    if (!is_array($merged)) {
        return $merged; // Not an array, return as is
    }

    foreach ($arrays as $array) {
        foreach ($array 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',
        'user' => 'root',
        'password' => '',
        'options' => ['charset' => 'utf8']
    ],
    'app' => [
        'name' => 'MyApp',
        'debug' => true
    ]
];

$userConfig = [
    'database' => [
        'user' => 'admin',
        'password' => 'newpass',
        'options' => ['port' => 3306] // New option
    ],
    'app' => [
        'debug' => false,
        'log_level' => 'info' // New setting
    ],
    'cache' => [ // Entirely new section
        'driver' => 'file'
    ]
];

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

// Output:
// Array
// (
//     [database] => Array
//         (
//             [host] => localhost
//             [user] => admin
//             [password] => newpass
//             [options] => Array
//                 (
//                     [charset] => utf8
//                     [port] => 3306
//                 )
//         )
//
//     [app] => Array
//         (
//             [name] => MyApp
//             [debug] => 
//             [log_level] => info
//         )
//
//     [cache] => Array
//         (
//             [driver] => file
//         )
//
// )
?>
How it works: Unlike PHP's native `array_merge_recursive()`, which converts conflicting non-array values into arrays, this custom function `array_merge_recursive_distinct()` intelligently merges associative arrays. It iterates through the input arrays, recursively merging sub-arrays when both the source and destination keys hold arrays, and overwriting scalar values. This is essential for merging configuration files or complex data structures where you want to combine settings without losing nested data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs