Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

The inquiry is basic. I have a foreach loop in my code:
foreach($array as $element) {
//code
}

In this loop, I need to respond otherwise when we are in first or last emphasis.

How to do this?
by

2 Answers

akshay1995
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++;
}
sandhya6gczb
Use this code to get the first and last iteration in each loop

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

end($array);
if ($key === key($array))
echo 'LAST ELEMENT!';
}

Login / Signup to Answer the Question.