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

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


If you prefer a solution that does not require the initialization of the counter outside the loop, then you can compare the current iteration key against the function that tells you the last / first key of the array.

PHP 7.3 and newer:

foreach ($array as $key => $element) {    if ($key === array_key_first($array)) {        echo 'FIRST ELEMENT!';    }    if ($key === array_key_last($array)) {        echo 'LAST ELEMENT!';    }}

PHP 7.2 and older:

foreach ($array as $key => $element) {    reset($array);    if ($key === key($array)) {        echo 'FIRST ELEMENT!';    }    end($array);    if ($key === key($array)) {        echo 'LAST ELEMENT!';    }}


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++;}


To find the last item, I find this piece of code works every time:

foreach( $items as $item ) {    if( !next( $items ) ) {        echo 'Last Item';    }}