Forum Moderators: coopster
But what if you want to do something special on the last item? Or on each item except the last one?
The code below illustrates using next() for this. It works on a copy of the original array, going "next" at each iteration. On the last item, there is no "next", so it returns FALSE.
<?php
$array = ['one','two','three','four','five'];
foreach($array as $v){
$lastone = next($array)===FALSE;
print($v);
if(!$lastone){
print(" and a ");
}
}
?>
I just learned this today, so I thought it would be nice to share. It came in handy today looping and rendering a list of things with stuff injected between them; but I didn't want a delimiter at the end of the list.
I suppose this could also be done using an array join, or a for-loop with a counter. But I found this to be a very satisfying technique which brought some joy to an otherwise boring Thursday.
>> I suppose this could also be done using an array join, or a for-loop with a counter.
While this example could have a join solution, there are other applications where something like a join wouldn't work. As for the for loop, you are going to probably get a much quicker result if you use that instead of the method you have described above. For instance, compared to your code above the following code runs almost twice as fast each time:
$count = count($array);
for($i = 0; $i < $count; $i++) {
echo $array[$i];
if($i != $count-2)
echo ' and a ';
}
When dealing with much larger arrays that could be a more significant time.
[edited by: eelixduppy at 11:27 pm (utc) on May 23, 2008]