Possible Duplicate:
How to determine the first and last iteration in a foreach loop?
what is the best way to establish that a foreach loop is in it's final loop, and perform different functions accordingly?
Possible Duplicate:
How to determine the first and last iteration in a foreach loop?
what is the best way to establish that a foreach loop is in it's final loop, and perform different functions accordingly?
The way I would approach this is to increment a variable and test that variable against the size of the array (count()
):
$i = 0;
$c = count($array);
foreach($array as $key => $value) {
$i++;
if ($i == $c) {
// last iteration
}
else {
// do stuff
}
}
This may, obviously, not be the most efficient method, though.
There are two ways of doing this:
for
loop instead, or an incrementing variable with the foreach loop to check if(count($someArr) - 1 == $currentIteration)
. If so, do that logic.hm... use this:
$i =0;
$c = count($employeeAges);
foreach( $employeeAges as $key => $value){
if($c-$i<=1){
//DO SOMETHING
}else{
//default for other loops
}
i++;
}