note 92752 deleted from function.implode by hholzgra

From: Date: Thu, 02 Aug 2012 13:22:22 +0000
Subject: note 92752 deleted from function.implode by hholzgra
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189765@lists.php.net to get a copy of this message
Note Submitter: ravenswd at gmail dot com ---- 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); ?>

« previous php.notes (#189765) next »