PHP

Deep Merge Multidimensional PHP Arrays

Learn how to recursively merge two or more multidimensional PHP arrays, handling both scalar and array values correctly, without losing data.

<?php

function array_deep_merge(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] = array_deep_merge($result[$key], $value);
            } else {
                $result[$key] = $value;
            }
        }
    }
    return $result;
}

$array1 = [
    'name' => 'Product A',
    'options' => [
        'color' => 'red',
        'size' => 'M'
    ],
    'tags' => ['electronics', 'gadget']
];

$array2 = [
    'price' => 29.99,
    'options' => [
        'size' => 'L',
        'material' => 'plastic'
    ],
    'tags' => ['new', 'best-seller']
];

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

// Expected Output:
// Array
// (
//     [name] => Product A
//     [options] => Array
//         (
//             [color] => red
//             [size] => L
//             [material] => plastic
//         )
//     [tags] => Array
//         (
//             [0] => new
//             [1] => best-seller
//         )
//     [price] => 29.99
// )

print_r($mergedArray);
How it works: This snippet provides a custom function `array_deep_merge` for recursively merging an arbitrary number of PHP arrays. Unlike `array_merge_recursive`, this function correctly overwrites scalar values with new ones and performs a deep merge for nested arrays with matching keys, rather than appending values. This is crucial for merging configuration arrays or default options where you want specific keys to be updated at any depth, ensuring a predictable merged result.

Need help integrating this into your project?

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

Hire DigitalCodeLabs