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
)
@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 Rigotti
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".
– Wallace Maxters