PHP

Recursively Merge Two PHP Arrays with Overwriting Scalars

Learn how to recursively merge two PHP arrays, intelligently combining sub-arrays while ensuring scalar values in the second array overwrite those in the first, preventing unwanted array nesting.

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

$arrayA = [
    'config' => [
        'theme' => 'dark',
        'db' => [
            'host' => 'localhost',
            'port' => 3306
        ]
    ],
    'users' => ['Alice', 'Bob']
];

$arrayB = [
    'config' => [
        'theme' => 'light',
        'db' => [
            'port' => 3307,
            'user' => 'root'
        ]
    ],
    'users' => ['Charlie']
];

$result = array_merge_recursive_distinct($arrayA, $arrayB);
print_r($result);

/*
Output:
Array
(
    [config] => Array
        (
            [theme] => light
            [db] => Array
                (
                    [host] => localhost
                    [port] => 3307
                    [user] => root
                )

        )

    [users] => Array
        (
            [0] => Charlie
        )

)
*/
How it works: This snippet provides a custom `array_merge_recursive_distinct` function that intelligently merges two arrays. Unlike PHP's built-in `array_merge_recursive` which creates new arrays for conflicting scalar keys, this function prioritizes the second array's scalar values and recursively merges sub-arrays. This ensures that configurations or settings are properly overwritten and combined without leading to unexpected nested arrays for simple string or numeric values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs