Hi Phil.
On Monday 13 April 2009, PJ wrote:
> Thanks for the suggestion, Mark. I've already experimented with count;
> you're close, but there is still a small glitch and that's in count();
> foreach doesn't give a damn about count so you can't use that - it is
> reset once inside the foreach loop.
Look again at the code - the count() is not inside the foreach, so it is
not reset, simply stored in $lastIndex for comparison.
If your array is associative then simply use another variable to find the
last value in the array - the code doesn't need to change much.
Try actually running the code below - it does work, as does the previous
version I posted if the array is not associative.
I'd prefer it if in future you didn't tell me that my code didn't work
without actually trying it - I tested that snippet before posting it, as I
did with the following.
HTH
Mark
<?php
// Non-associative array (the code I posted previously).
$a = array('1','2','3');
$lastIndex = count($a) - 1;
$outputString = '';
foreach ($a as $index => $value) {
if ($index != $lastIndex) {
$outputString .= "$value, ";
} else {
$outputString = rtrim($outputString,', '); // Strip last comma.
$outputString .= " & $value<br />";
}
}
echo $outputString;
// Associative array (changed only very slightly).
$a = array('martha' => '1','jock' => '2','dave' => '3');
$lastIndex = count($a);
$counter = 0;
$outputString = '';
foreach ($a as $index => $value) {
$counter++;
if ($counter != $lastIndex) {
$outputString .= "$value, ";
} else {
$outputString = rtrim($outputString,', '); // Strip last comma.
$outputString .= " & $value<br />";
}
}
echo $outputString;
?>
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php