← Back to all snippets
PHP

Recursively Merge Multiple Arrays with Value Overwriting

Implement a custom PHP function to recursively merge two or more arrays, intelligently combining nested arrays and ensuring later values overwrite earlier ones, unlike `array_merge_recursive`.

function arrayMergeRecursiveDistinct(array ...$arrays): array
{
    $result = [];
    foreach ($arrays as $array) {
        foreach ($array as $key => $value) {
            if (is_array($value) && isset($result[$key]) && is_array($result[$key])) {
                $result[$key] = arrayMergeRecursiveDistinct($result[$key], $value);
            } else {
                $result[$key] = $value;
            }
        }
    }
    return $result;
}

$array1 = [
    'a' => 1,
    'b' => [
        'b1' => 'old_b1',
        'b2' => 'common_b2',
    ],
    'c' => 3
];

$array2 = [
    'b' => [
        'b2' => 'new_b2',
        'b3' => 'new_b3',
    ],
    'd' => 4
];

$mergedArray = arrayMergeRecursiveDistinct($array1, $array2);
// var_dump($mergedArray);
/* Expected Output:
[
    "a" => 1,
    "b" => [
        "b1" => "old_b1",
        "b2" => "new_b2", // Overwritten
        "b3" => "new_b3"
    ],
    "c" => 3,
    "d" => 4
]
*/
How it works: The `arrayMergeRecursiveDistinct` function provides a custom recursive merge for multiple arrays. Unlike PHP's built-in `array_merge_recursive` which appends values into nested arrays, this function ensures that if a key exists in subsequent arrays and both values are arrays, it recursively merges them. If values are not arrays or one of them isn't, the later value simply overwrites the earlier one. This behavior is highly useful for scenarios like merging configuration settings where newer values should take precedence.

Need help integrating this into your project?

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

Hire DigitalCodeLabs