There are two differences between + and the array_merge () :
Operator + :
When we use this operator if we have elements with the same keys (whether numerical or not), the left array values 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;
Result:
(
[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 $a
were considered ignoring elements in $b
.
With array_merge () :
Here is the opposite, in case of having equal (non-numeric) keys the ones in the array on the right prevail over those on the left. In the case of having numeric keys, and being the same keys in both arrays, they are redefined 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);
Result:
(
[a] => pear
[b] => strawberry
[0] => lol
[c] => cherry
[1] => lil
)