Seva Lapsha at Work & around

Core & Web Development & Design

PHP: array_merge versus array union operator (+)

with 2 comments

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.

Written by Seva

2010-07-22 (July 22) at 11:10:52

Posted in development, php

2 Responses

Subscribe to comments with RSS.

  1. 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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 102 other followers