What's the difference between array_merge and array + array?

04/14/2020 06:00:02

A fairly simple question. What's the difference between:

$merged = array_merge($array1, $array2);

and

$merged = $array1 + $array2;

?

Verified Answer (67 Votes)

03/22/2011 21:05:41

The difference is:

The + operator takes the union of the two arrays, whereas the array_merge function takes the union BUT the duplicate keys are overwritten.

67

Answer #2 (84 Votes)

05/29/2014 15:12:44

Here's a simple illustrative test:

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


$ar2 = [
   0  => '2-0',
   1  => '2-1',
  'b' => '2-b',
  'c' => '2-c'
];

print_r($ar1+$ar2);

print_r(array_merge($ar1,$ar2));

with the result:

Array
(
  [0] => 1-0
  [a] => 1-a
  [b] => 1-b
  [1] => 2-1
  [c] => 2-c
)
Array
(
  [0] => 1-0
  [a] => 1-a
  [b] => 2-b
  [1] => 2-0
  [2] => 2-1
  [c] => 2-c
)

Notice that duplicate non-numeric keys will take the first value using the union operator but the later one using the array_merge.

For numeric keys, the first value will be used with the union operator whereas the all the values will be used with the array_merge, just reindexed.

I generally use union operator for associative arrays and array_merge for numeric. Of course, you can just as well use the array_merge for associative, just that the later values overwrite earlier ones.

84

Answer #3 (51 Votes)

03/22/2011 21:06:18

array_merge() causes all numeric keys found in the input arrays to be reindexed in the resultant array. The union operator + does not cause a reindex.

51
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.