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?
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).
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: <?
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.
foreach ($array as $key => $element) { if ($key === array_key_first($array)) { echo 'FIRST ELEMENT!'; } if ($key === array_key_last($array)) { echo 'LAST ELEMENT!'; } }
foreach ($array as $key => $element) { reset($array); if ($key === key($array)) { echo 'FIRST ELEMENT!'; } end($array); if ($key === key($array)) { echo 'LAST ELEMENT!'; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With