The easiest way to establish that the foreach loop in it is the final iteration

Possible duplicate:
How to determine the first and last iteration in a foreach loop?

What is the best way to establish that the foreach loop is in it in the final loop and performs various functions accordingly?

+3
source share
4 answers

The way I would like to approach this is to increase the increment of the variable and check this variable for 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 effective method.

+3
source

There are two ways to do this:

  • , , .
  • for foreach if(count($someArr) - 1 == $currentIteration). , .
+1

IMHO the best way is to use a loop forfor such cases.

0
source

um ... use this:

 $i =0;
 $c = count($employeeAges);
    foreach( $employeeAges as $key => $value){
    if($c-$i<=1){
          //DO SOMETHING
        }else{
          //default for other loops
        }
        i++;
     }
0
source

Source: https://habr.com/ru/post/1793094/


All Articles