Bug #68969 [Nab]: Implode

From: Date: Sun, 01 Feb 2015 22:39:46 +0000
Subject: Bug #68969 [Nab]: Implode
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-190390@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=68969&edit=1 ID: 68969 Updated by: yohgaki@php.net Reported by: pl dot lamballais at flashover dot fr Summary: Implode Status: Not a bug Type: Bug Package: *General Issues Operating System: Debian PHP Version: 5.5.21 Block user comment: N Private report: N New Comment: pl, it's not specific to implode(), but it's nature of PHP array. It's documented in the manual, I suppose. Previous Comments: ------------------------------------------------------------------------ [2015-02-01 22:36:51] pl dot lamballais at flashover dot fr OK, in that case, maybe a note on 'implode' manual must be good in order to remember this feature which can give strange results. ------------------------------------------------------------------------ [2015-02-01 21:37:32] rasmus@php.net 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 ------------------------------------------------------------------------ [2015-02-01 21:36:05] yohgaki@php.net PHP array is not an array in terms of array of values. i.e. Numerical index is not a address of element. It's a ordered list. Numerical index does not define order of values. ------------------------------------------------------------------------ [2015-02-01 21:29:14] 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"; ?> ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=68969&edit=1

« previous php.bugs (#190390) next »