PHP

Deep Merge Multiple PHP Arrays Recursively

Combine multiple PHP arrays, including nested arrays, into a single array using `array_merge_recursive` while correctly handling duplicate keys.

<?php

function deepMergeArrays(array ...$arrays): array
{
    if (count($arrays) === 0) {
        return [];
    }
    return array_merge_recursive(...$arrays);
}

$array1 = [
    'data' => ['a' => 1, 'b' => 2],
    'settings' => ['theme' => 'dark', 'font' => 'Arial']
];

$array2 = [
    'data' => ['c' => 3],
    'settings' => ['font' => 'Verdana', 'lang' => 'en'],
    'users' => [1, 2]
];

$mergedArray = deepMergeArrays($array1, $array2);

print_r($mergedArray);

// Output:
// Array
// (
//     [data] => Array
//         (
//             [a] => 1
//             [b] => 2
//             [c] => 3
//         )
//
//     [settings] => Array
//         (
//             [theme] => dark
//             [font] => Array
//                 (
//                     [0] => Arial
//                     [1] => Verdana
//                 )
//
//             [lang] => en
//         )
//
//     [users] => Array
//         (
//             [0] => 1
//             [1] => 2
//         )
//
// )
How it works: When you need to combine arrays, especially those with nested structures, `array_merge_recursive()` is invaluable. Unlike `array_merge()` which overwrites scalar values with the same string keys, `array_merge_recursive()` attempts to merge them into a new array. For numeric keys, values are appended, while for string keys, if values are arrays, they are merged recursively; otherwise, they become an array of both values. This is crucial for merging configuration files or complex data objects.

Need help integrating this into your project?

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

Hire DigitalCodeLabs