What does array + do in PHP?

Written on 2020-06-05

In PHP it's possible to do array + array. The "plus" sign is a shorthand way of merging arrays, but there's a difference in how they are merged compared to using array_merge.

Let's imagine these two arrays:

$first = [
    'a',
    'b',
];

$second = [
    'c',
];

Merging them using + would result in the following:

$first + $second;

// ['a', 'b']

While using array_merge, would result in this:

array_merge($first, $second);

// ['a', 'b', 'c']

What's happening here is that array_merge will override existing keys, while + will not. In other words: when a key exists in the first array, + will not merge an item with the same key from another array into the first one.

In our example, both arrays actually had numerical keys, like so:

$first = [
    0 => 'a',
    1 => 'b',
];

$second = [
    0 => 'c',
];

Which explains why $first + $second doesn't add 'c' as an element: there already is an item with index 0 in the original.

The same applies for textual keys:

$first = [
    'a' => 'a',
    'b' => 'b',
];

$second = [
    'a' => 'a - override',
];

$first + $second;

// ['a' => 'a', 'b' => 'b']

And finally, + also works with nested arrays:

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

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

Using + will keep the original value, while array_merge would override it.

One more thing to mention is that + will apply the same behaviour when merging multidimensional arrays.

Join over 14k subscribers on my mailing list: I write about PHP, programming, and keep you up to date about what's happening on this blog. You can subscribe by sending an email to brendt@stitcher.io.

Things I wish I knew when I started programming

Things I wish I knew when I started programming cover image

This is my newest book aimed at programmers of any skill level. This book isn't about patterns, principles, or best practices; there's actually barely any code in it. It's about the many things I've learned along the way being a professional programmer, and about the many, many mistakes I made along that way as well. It's what I wish someone would have told me years ago, and I hope it might inspire you.

Read more

Comments

Loading…
No comments yet, be the first!
Noticed a tpyo? You can submit a PR to fix it.
HomeRSSNewsletterDiscord© 2025 stitcher.io