"how to determine the first and last iteration in a foreach loop?" Code Answer

3

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++;
}
By etsous on September 16 2022

Answers related to “how to determine the first and last iteration in a foreach loop?”

Only authorized users can answer the search term. Please sign in first, or register a free account.