Often times I will want to do something different in a foreach loop on the last iteration. The code below is a good standard way of handling this…
$last_item = end($array); $last_item = each($array); reset($array); foreach($array as $key => $value){ // code executed during standard iteration if($value == $last_item['value'] && $key == $last_item['key']){ // code executed on the // last iteration of the foreach loop } }
Note that in the if clause I check to make sure that both the key AND the value of the last item iterated match. If you were to check simply the value you could end up getting a match before the last iteration.
The above code should help you when trying to do something different on the last element, last value, last iteration, last loop, or last item of a PHP foreach loop.

great!
I’ve spent hours looking for this solution,
nice working solution, but I wonder about the running time with large algorithms
any way,
Nice work
If you’re worried about runtime, the worst case scenario for this is O(n). A hash table could be useful if you’re expecting lots of values.
Thanks very much for this code. It didn’t work for me.
I have the following array:
[field_author] => Array
(
[0] => Array
(
[value] => 529
[view] => Barak Obama
)
[1] => Array
(
[value] => 530
[view] => Dmitry Medvedev
)
[2] => Array
(
[value] => 531
[view] => Gordon Brown
)
)
…and modified your code as follows:
$last_item = end($node->field_author);
$last_item = each($node->field_author);
reset($node->field_author);
foreach($node->field_author as $key => $value){
// code executed during standard iteration
print ($value['view'].', ');
if($node->field_author == $last_item['value'] && $key == $last_item['key']){
// code executed on the
// last iteration of the foreach loop
print $value['view'];
}
}
I get the following result:
Barak Obama, Dmitry Medvedev, Gordon Brown,
I don’t want the last comma
Any suggestions?
Thanks again,
Scott
PS. What I’d really like to be able to do is account for 1, 2, 3, 4 or more author cases, each having their own link. For example:
Barak Obama
Barak Obama and Dmitry Medvedev
Barak Obama, Dmitry Medvedev and Gordon Brown
Barak Obama, Dmitry Medvedev, Nicolas Sarkozy and Gordon Brown
//much simpler , time less algorithm
$i = 0;
$length = count($arrray) – 1;
foreach($array as $key => $value){
‘;
if( $i != $length )
{
echo ‘Woooooooohooo iam not the last’;
}
else
{
echo ‘sadly iam the last one
}
$i++;
}