If your using a foreach loop, unless you for a reference, PHP will make a copy of the array to use it the loop.
So, when I need to take a different action for the last element in the array I use the following:
<?php
$ary = explode(',','a,b,c,d,e,f,g');
foreach($ary as $a){
print 'letter ' . $a;
if(next($ary)){
print '<br>';
}else{
print '<br>dun!';
}
}
?>
Output:
letter a
letter b
letter c
letter d
letter e
letter f
letter g
dun!
NOTE::
PHP5 has added an ability to reference the variable in a foreach like:
<?php
foreach($ary as &$a){}
?>
this will probably cause undesired results when using the method above.
also if the array is changed in any way as to cause the length of the original array to become different then the copy, it will not work.
Consider the following example:
<?php
$ary = explode(',','a,b,c,d,e,f,g');
foreach($ary as $a){
print 'letter ' . $a;
if(next($ary)){
unset($ary[count($ary) - 1]);
print '<br>';
}else{
print '<br>dun!';
}
}
?>
output:
letter a
letter b
letter c
letter d
dun!letter e
dun!letter f
dun!letter g
dun!