php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #68969 Implode
Submitted: 2015-02-01 21:29 UTC Modified: 2015-02-01 22:39 UTC
From: pl dot lamballais at flashover dot fr Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 5.5.21 OS: Debian
Private report: No CVE-ID: None
 [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";

?>


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-02-01 21:36 UTC] yohgaki@php.net
-Status: Open +Status: Not a bug
 [2015-02-01 21:36 UTC] 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:37 UTC] 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 22:36 UTC] 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 22:39 UTC] yohgaki@php.net
pl, it's not specific to implode(), but it's nature of PHP array. It's documented in the manual, I suppose.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 01:00:01 2026 UTC