Timeline Taxi Out now: my sci-fi novel Timeline Taxi is published!

How to merge multidimensional arrays in PHP?

If you want to join two multidimensional arrays in PHP, you should still use array_merge, and not array_merge_recursive. Confused? So was I. Let's explain what's happening.

Let's first explain what array_merge_recursive does, take for example these two arrays:

$first = [
    'key' => 'original'
];

$second = [
    'key' => 'override'
];

Using array_merge_recursive will result in the following:

array_merge_recursive($first, $second);

// [
//     'key' => [
//         'original',
//         'override',
//     ],
// ]

Instead of overriding the original key value, array_merge_recursive created an array, with the original and new value both in it.

While that looks strange in this simple example, it's actually more useful in cases where one of the values already is an array, and you want to merge another item in that array, instead of overriding it.

$first = [
    'key' => ['original']
];

$second = [
    'key' => 'override'
];

In this case, array_merge_recursive will yield the same result as the first example: it takes the value from the $second array, and appends it to the value in the $first array, which already was an array itself.

array_merge_recursive($first, $second);

// [
//     'key' => [
//         'original',
//         'override',
//     ],
// ]

So if you want to merge multidimensional arrays, you can simply use array_merge, it can handle multiple levels of arrays just fine:

$first = [
    'level 1' => [
        'level 2' => 'original'
    ]
];

$second = [
    'level 1' => [
        'level 2' => 'override'
    ]
];

array_merge($first, $second);

// [  
//     'level 1' => [
//         'level 2' => 'override'
//     ]
// ]

All of that being said, you could also use the + operator to merge multidimensional arrays, but it will work slightly different compared to array_merge.

Noticed a tpyo? You can submit a PR to fix it. If you want to stay up to date about what's happening on this blog, you can subscribe to my mailing list: send an email to brendt@stitcher.io, and I'll add you to the list.