Is there a difference when merging two arrays with array_merge or with "+"?

Asked

Viewed 3,557 times

7

I used to unite two arrays, in PHP, using the function array_merge:

$arr3 = array_merge($arr1, $arr2);

However, more recently I have seen unions of arrays with + (plus sign):

$arr3 = $arr1 + $arr2;

Is there any difference between these two methods?

  • 1

    @Wallacemaxters worth the touch, when I had written the title this post did not appear. However, the answer is good, so I’ll validate it anyway. :)

  • Rodrigo, no problem. It’s better because the questions refer to each other. In this case, you used the operator "+" in the title, and I put "sum".

1 answer

14


There are two differences between + and the array_merge():

Operator +:

When we use this operator in the case of elements with the same keys (whether they are numerical or not) the values of the left array prevail over those of the right array. Consider the example:

$a = array("a" => "apple", "b" => "banana", 'lol');
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry", 'lil');

$merged = $a + $b;

Upshot:

(
    [a] => apple
    [b] => banana
    [0] => lol
    [c] => cherry
)

As you can see, in elements with the same key in both arrays ($a and $b), only those of $a were considered, ignoring the elements in $b.

With array_merge():

Here is the opposite, in the case of equal (non-numerical) key terms, those of the right array prevail over those of the left. In the case of numerical key terms, and being the same keys in both arrays they are reset so that both elements are included in the merge:

$a = array("a" => "apple", "b" => "banana", 'lol');
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry", 'lil');

$merged = array_merge($a, $b);

Upshot:

(
    [a] => pear
    [b] => strawberry
    [0] => lol
    [c] => cherry
    [1] => lil
)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.