Skip to content
Advertisement

PHP How to determine the first and last iteration in a foreach loop?

The question is simple. I have a foreach loop in my code:

foreach($array as $element) {
    //code
}

In this loop, I want to react differently when we are in first or last iteration.

How to do this?

Advertisement

Answer

You could use a counter:

$i = 0;
$len = count($array);
foreach ($array as $item) {
    if ($i == 0) {
        // first
    } else if ($i == $len - 1) {
        // last
    }
    // …
    $i++;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement