note 96688 deleted from function.array-merge by danbrown
| From: | danbrown@php.net | Date: | Thu, 11 Mar 2010 17:55:05 +0000 |
| Subject: | note 96688 deleted from function.array-merge by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-166918@lists.php.net to get a copy of this message | ||
Note Submitter: the DOT ganong AT gmail DOT com
----
Just to highlight Alec's note as well as add a clear example:
"Note that if you put a number as a key in an array, it is eventually converted to an int even
if you cast it to a string or put it in quotes." - Alec
For instance:
<?php
$array1 = array(
'0' => 'zero'
);
$array2 = array(
'01' => 'one',
'02' => 'two',
'3' => 'three',
'4' => 'four'
);
$array3 = array_merge( $array1, $array2 );
print_r( $array3 );
/*
Array
(
[0] => zero
[01] => one
[02] => two
[1] => three
[2] => four
)
*/
$array4 = $array1 + $array2;
print_r( $array4 );
/*
Array
(
[0] => zero
[01] => one
[02] => two
[3] => three
[4] => four
)
*/
?>
So the '3' are '4' are converted to ints (even though they are strings
originally because of the quotes) and reordered with array_merge, but '01' and
'02' are not. This re-enforces that if you want to preserve keys and just want to append
an array (and know there won't be collisions or don't want to overwrite array1's
elements) use the + operator.
Like it says in the doc: "If you want to append array elements from the second array to the
first array while not overwriting the elements from the first array and not re-indexing, use the +
array union operator"