PHP: array_merge versus array union operator (+)
It comes that even experienced PHP developers don’t remember what is the difference between running array_merge((array)$a1, (array)$a2) and (array)$a1+(array)$a2. The answer is given @ php.net, no need to guess and argue.
Here is the difference:
Array Union: The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
array_merge(): 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. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
It should also be mentioned that using the array union operator also treats numeric keys (i.e. of a non-associative array) the same as associative keys, which is somewhat counter-intuitive.
mdpatrick
2012-03-04 (March 4) at 07:54:20
Not at all. Array union is well defined, while array_merge is the bad magician.
Seva
2012-03-05 (March 5) at 02:24:48