note 96688 added to function.array-merge

From: Date: Thu, 11 Mar 2010 17:12:17 +0000
Subject: note 96688 added to function.array-merge
Groups: php.notes 
Request: Send a blank email to php-notes+get-166917@lists.php.net to get a copy of this message
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" ---- Server IP: 192.41.40.227 Probable Submitter: 67.79.167.164 ---- Manual Page -- http://www.php.net/manual/en/function.array-merge.php Edit -- https://master.php.net/note/edit/96688 Del: integrated -- https://master.php.net/note/delete/96688/integrated Del: useless -- https://master.php.net/note/delete/96688/useless Del: bad code -- https://master.php.net/note/delete/96688/bad+code Del: spam -- https://master.php.net/note/delete/96688/spam Del: non-english -- https://master.php.net/note/delete/96688/non-english Del: in docs -- https://master.php.net/note/delete/96688/in+docs Del: other reasons-- https://master.php.net/note/delete/96688 Reject -- https://master.php.net/note/reject/96688 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166917) next »