PHP – How to determine the first and last iteration in a for each loop
Table Of Content
The question is simple. we have a for each loop in our code:
In this loop, we want to react differently when we are in first or last iteration.
How to do this?
Php loops for each
Use a counter:
Another example:
[ad type=”banner”]Try this code:
If your array has unique array values, then determining the first and last element is trivial:
This works if last and first elements are appearing just once in an array, otherwise you get false positives. Therefore, you have to compare the keys (they are unique for sure).
Update: Some people are concerned about performance and/or modifying the array pointer inside a foreach loop.
For those, you can cache the key value before the loop.
A more simplified version of the above and presuming you’re not using custom indexes…
[ad type=”banner”]If you only need just the first element then you may try this code.