PHP

Deep Merge Two PHP Arrays Recursively

Learn how to perform a robust, deep merge of two PHP arrays, including nested arrays, where values from the second array take precedence.

<?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 = [
    'settings' => [
        'theme' => 'dark',
        'notifications' => [
            'email' => true,
            'sms' => false,
        ],
    ],
    'user' => 'admin',
    'permissions' => ['read', 'write'],
];

$array2 = [
    'settings' => [
        'notifications' => [
            'sms' => true,
            'push' => true,
        ],
        'language' => 'en',
    ],
    'user' => 'guest',
    'permissions' => ['read'], // This will overwrite, not append
    'new_key' => 'value',
];

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

/* Expected output:
Array
(
    [settings] => Array
        (
            [theme] => dark
            [notifications] => Array
                (
                    [email] => true
                    [sms] => true
                    [push] => true
                )

            [language] => en
        )

    [user] => guest
    [permissions] => Array
        (
            [0] => read
        )

    [new_key] => value
)
*/
?>
How it works: This `array_merge_recursive_distinct` function provides a custom solution for deep merging two arrays. Unlike `array_merge_recursive`, which appends values for non-associative arrays, this function prioritizes values from the second array. It recursively merges nested arrays and overwrites scalar values from the first array with corresponding values from the second.

Need help integrating this into your project?

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

Hire DigitalCodeLabs