Forum Moderators: coopster

Message Too Old, No Replies

foreach(), with a twist on the last item

a code nugget for you to enjoy

         

httpwebwitch

8:17 pm on May 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



foreach() is great for iterating through an array.

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.

eelixduppy

8:44 pm on May 22, 2008 (gmt 0)



Thanks for sharing your solution! :)

>> 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]

dreamcatcher

6:58 am on May 23, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yeah, I would go with the second option too. Although, shouldn`t $count-2 be $count-1 for the last entry?

dc