[development] += on arrays

Jeremy Epstein jazepstein at gmail.com
Wed Jan 18 02:28:55 UTC 2006


First of all, you should remember this fundamental difference between
array_merge() and the array + operator:

" Don't forget that numeric keys will be renumbered! ... If you want
to completely preserve the arrays and just want to append them to each
other, use the + operator."
(from http://www.php.net/manual/en/function.array-merge.php)

Personally, I find that the re-indexing behaviour of array_merge() is
often not what I want, so I'm finding that I use the + operator more
and more.

Also, consider these two examples:

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

In the first example (assuming that the keys aren't numeric), $array2
is guaranteed to have all its values preserved; in the second example
(no matter what type the keys are), $array1 is guaranteed this. So...

On 1/18/06, Larry Garfield <larry at garfieldtech.com> wrote:
> So... array_merge($a, $b) favors $a, while $a += $b favors $b?  Wouldn't that
> mean that
>
> array_merge($a, $b) == $b += $a

It's the other way around, Larry. :-) But the two operations are only
equivalent IF there are no numeric keys! If there are, then
array_merge() behaves differently (and stupidly, IMO).

On a related note: perhaps we should agree on a recommended way (i.e.
one of the above two ways) of merging arrays in Drupal? I'd like to
see the + operator encouraged, as it's more predictable, and
(according to chx) is also faster. But I don't know that we can outlaw
array_merge() altogether (as we did with array_key_exists() recently)
as there may still be times when it's needed, since it is a bit
different to the + operator.

Jaza.


More information about the development mailing list