|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2015-02-01 21:29 UTC] pl dot lamballais at flashover dot fr
Description: ------------ --- From manual page: http://www.php.net/function.implode --- Get an array that I fill with values, and then want to implode it. I notice that if I fill the array in logical order (index 1,2,3,4,5,6,7,8,9), implode is OK. But if I fill it in an other order (eg index 1,4,7,2,5,8,3,6,9), implode don't respect the index. Test script: --------------- <?php for ($x=0; $x < 50; $x=$x+3) { $tab[$x] = "A"; } for ($x=1; $x < 50; $x=$x+3) { $tab[$x] = "B"; } for ($x=2; $x < 20; $x=$x+3) { $tab[$x] = "C"; } for ($x=0; $x < 50; $x++) { // Here is correct result we expect echo $tab[$x]; } $str = implode('',$tab); echo "<br>".$str."<br>\n"; ?> PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 07 08:00:02 2026 UTC |
Arrays in PHP are ordered meaning the order is maintained. So if you do this: php > $a = [3=>1, 1=>2, 2=>3]; And you iterate over the array you get: php > foreach($a as $k=>$v) echo "a[$k] = $v\n"; a[3] = 1 a[1] = 2 a[2] = 3 That is, the order you created the array is maintained. Of course, you can loop over the indices if you wish: php > for($k=1; $k<=3; $k++) echo "a[$k] = {$a[$k]}\n"; a[1] = 2 a[2] = 3 a[3] = 1 But, implode() will simply implode the raw ordered array. If you want it sorted by its key, then do that before you call implode(). eg. php > echo implode($a); 123 php > ksort($a); php > echo implode($a); 231