note 92752 modified in function.implode by danbrown

From: Date: Fri, 07 Aug 2009 14:45:38 +0000
Subject: note 92752 modified in function.implode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-159188@lists.php.net to get a copy of this message
As "john" pointed out on 2004 Apr 26, implode does not always work in a way that could be considered intuitive. You may need to sort your elements with ksort, or write a longer routine to fill in any "gaps". See this example: <?php $a = array(1=>'one', 7=>'seven', 5=>'five'); $b = implode (',', $a); ksort ($a); $c = implode (',', $a); $highest = max(array_keys($a)); for ($i = 0; $i <= $highest; ++$i): if (! isset($a[$i])): $a[$i] = ''; endif; endfor; ksort ($a); $d = implode (',', $a); print "\$b = '$b'<br>\n"; print "\$c = '$c'<br>\n"; print "\$d = '$d'<br>\n"; /* output: $b = 'one,seven,five' $c = 'one,five,seven' $d = ',one,,,,five,,seven' */ ?> Or, as a function: <?php function ensure (&$a, $filler = '') { // given: array $a with numerical keys // return: $a with keys sorted numerically and any gaps filled-in $highest = max(array_keys($a)); for ($i = 0; $i <= $highest; ++$i): if (! isset($a[$i])): $a[$i] = $filler; endif; endfor; ksort ($a); } // end function ensure // usage: // ensure($foo); // ensure($bar, 0); ?> --was-- As "john" pointed out on 2004 Apr 26, implode does not always work in a way that could be considered intuitive. You may need to sort your elements with ksort, or write a longer routine to fill in any "gaps". See this example: <?php $a = array(1=>'one', 7=>'seven', 5=>'five'); $b = implode (',', $a); ksort ($a); $c = implode (',', $a); $highest = max(array_keys($a)); for ($i = 0; $i <= $highest; ++$i): if (! isset($a[$i])): $a[$i] = ''; endif; endfor; ksort ($a); $d = implode (',', $a); print "\$b = '$b'<br>\n"; print "\$c = '$c'<br>\n"; print "\$d = '$d'<br>\n"; /* output: $b = 'one,seven,five' $c = 'one,five,seven' $d = ',one,,,,five,,seven' */ ?> http://php.net/manual/en/function.implode.php

« previous php.notes (#159188) next »