Is there a difference when joining two arrays with array_merge or with "+"? [duplicate]

6

I used to merge two arrays into PHP using the array_merge function:

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

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

$arr3 = $arr1 + $arr2;

Is there any difference between these two methods?

    
asked by Rodrigo Rigotti 27.06.2016 в 11:22

1 answer

7

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
)
    
27.06.2016 / 12:07