On Tuesday 17 January 2006 20:28, Jeremy Epstein wrote:
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@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).
Ah ha. So I was backward but had the right idea. :-) The direction I'm going is...
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.
Exactly. If array_merge($a, $b) == $b += $a iff $a and $b are strictly associative arrays, and += is substantially faster, and Drupal uses associative arrays a LOT, it seems like this is a good language-level optimization to make and recommend. -- Larry Garfield AIM: LOLG42 larry@garfieldtech.com ICQ: 6817012 "If nature has made any one thing less susceptible than all others of exclusive property, it is the action of the thinking power called an idea, which an individual may exclusively possess as long as he keeps it to himself; but the moment it is divulged, it forces itself into the possession of every one, and the receiver cannot dispossess himself of it." -- Thomas Jefferson