4

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?

Community
  • 1
  • 1
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
  • 1
    Duplicate of at least [How to determine the first and last iteration in a foreach loop?](http://stackoverflow.com/questions/1070244), [in foreach, isLastItem() exists?](http://stackoverflow.com/questions/4943719), [How do you find the last element of an array while iterating using a foreach loop in php ?](http://stackoverflow.com/questions/665135) and [probably a lot more](http://stackoverflow.com/search?q=%5Bphp%5D+foreach+last). – Gumbo Feb 18 '11 at 17:15

4 Answers4

5

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.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • and what is a purpose of such stuff, if we already have for cycle? – UmmaGumma Feb 18 '11 at 17:22
  • @Ashot: the purpose of 'such stuff' is to answer the question as it was asked. I assumed, perhaps unfairly, that the OP knew of, and chose not to use, a `for` loop for a particular reason. – David Thomas Feb 18 '11 at 17:29
1

There are two ways of doing this:

  1. Determine what the last value of the array is before entering the loop, and on each iteration compare the current item to that previously-identified one.
  2. Use a for loop instead, or an incrementing variable with the foreach loop to check if(count($someArr) - 1 == $currentIteration). If so, do that logic.
Colin O'Dell
  • 8,386
  • 8
  • 38
  • 75
0

IMHO the best way is to use for loop for such cases.

UmmaGumma
  • 5,633
  • 1
  • 31
  • 45
0

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++;
     }
Sanosay
  • 536
  • 5
  • 18