Array_merge versus +

Elly picture Elly · Aug 14, 2011 · Viewed 45k times · Source

When I use array_merge() with associative arrays I get what I want, but when I use them with numerical key arrays the keys get changed.

With + the keys are preserved but it doesn't work with associative arrays.

I don't understand how this works, can anybody explain it to me?

Answer

Christopher Armstrong picture Christopher Armstrong · Aug 14, 2011

Because both arrays are numerically-indexed, only the values in the first array will be used.

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

http://php.net/manual/en/language.operators.array.php

array_merge() has slightly different behavior:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

http://php.net/manual/en/function.array-merge.php