Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

foreach

php

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?

like image 987
mehdi Avatar asked Jul 01 '09 16:07

mehdi


People also ask

Which is the fastest while for foreach () for of?

Correctly used, while is the fastest, as it can have only one check for every iteration, comparing one $i with another $max variable, and no additional calls before loop (except setting $max) or during loop (except $i++; which is inherently done in any loop statement).

What is the correct syntax of foreach loop?

The foreach loop is mainly used for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to $value, and the array pointer is advanced by one to go the next element in the array. Syntax: <?


1 Answers

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!';     } } 
like image 191
Rok Kralj Avatar answered Oct 12 '22 08:10

Rok Kralj