- PHP How to determine the first and last iteration in a foreach loop?
- 21 Answers 21
- PHP 7.3 and newer:
- PHP 7.2 and older:
- Determine the First and Last Iteration in a Foreach Loop in PHP
- PHP foreach() Syntax
- Get the First and Last Item in a foreach() Loop in PHP
- Use Counter in PHP foreach Loop
- Use array_key_first() and array_key_last() in PHP Loop
- Finding last entry in a foreach() process
- 5 Answers 5
PHP How to determine the first and last iteration in a foreach loop?
You should update the question with PHP. Javascript has forEach loop too. Viewers can get a misleading answer.
@Maidul True, in google it’s not clear at all that it’s about PHP so I added the word «PHP» to the title for clarity.
21 Answers 21
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:
PHP 7.2 is already EOL (end of life), so this is here just for historic reference. Avoid using.
foreach ($array as $key => $element) < reset($array); if ($key === key($array)) < echo 'FIRST ELEMENT!'; >end($array); if ($key === key($array)) < echo 'LAST ELEMENT!'; >>
This should bubble all the way to the top because it is the right answer. Another advantage of these functions over using array_shift and array_pop is that the arrays are left intact, in case they are needed at a later point. +1 for sharing knowledge just for the sake of it.
this is definitely the best way if you’re wanting to keep your code clean. I was about to upvote it, but now I’m not convinced the functional overhead of those array methods is worth it. If we’re just talking about the last element then that is end() + key() over every iteration of the loop — if it’s both then that’s 4 methods being called every time. Granted, those would be very lightweight operations and are probably just pointer lookups, but then the docs do go on to specify that reset() and end() modify the array’s internal pointer — so is it quicker than a counter? possibly not.
I don’t think you should issue reset($array) inside a foreach. From the official documentation (www.php.net/foreach): «As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.» And reset does precisely that (www.php.net/reset): «Set the internal pointer of an array to its first element»
@GonçaloQueirós: It works. Foreach works on a copy of array. However, if you are still concerned, feel free to move the reset() call before the foreach and cache the result in $first .
I don’t get why you all upvote this. Just use a boolean for «first» thats just better than everything else. The accepted answer is the way to go without running into «special cases».
$i = 0; $len = count($array); foreach ($array as $item) < if ($i == 0) < // first >else if ($i == $len - 1) < // last >// … $i++; >
I do not think downvoting should take place here as this is also working correctly and is still not so rubbish as using array_shift and array_pop . Though this is the solution I’d came up if I had to implement such a thing, I’d stick with the Rok Kralj’s answer now on.
@Twan How is point #3 right? Or relevant at all to this question since it involves HTML? This is a PHP question, clearly. and when it comes to mark-up semantics, it’s down to a much deeper facts than «a proper blahblah is always better than blahblah (this is not even my opinion, it’s pure fact)»
To find the last item, I find this piece of code works every time:
@Kevin Kuyl — As mentioned by Pang above, if the array contains an item that PHP evaluates as false (i.e. 0, «», null) this method will have unexpected results. I’ve amended the code to use ===
this is mostly very awesome but to clarify to problem others are pointing out it will invariably fail with an array like [true,true,false,true] . But personally I will be using this anytime I am dealing with an array that doesn’t contain boolean false .
next() should NEVER be used inside a foreach loop. It messes up the internal array pointer. Check out the documentation for more info.
A more simplified version of the above and presuming you’re not using custom indexes.
$len = count($array); foreach ($array as $index => $item) < if ($index == 0) < // first >else if ($index == $len - 1) < // last >>
Version 2 — Because I have come to loathe using the else unless necessary.
$len = count($array); foreach ($array as $index => $item) < if ($index == 0) < // first // do something continue; >if ($index == $len - 1) < // last // do something continue; >>
This is best answer for me but should be condensed, no point declaring length outside the foreach loop: if ($index == count($array)-1) < . >
@peteroak Yes actually it would technically hurts performance, and depending what your counting or how many loops could be significant. So disregard my comment 😀
@peteroak @Andrew The total number of elements in an array is stored as a property internally, so there would not be any performance hits by doing if ($index == count($array) — 1) . See here.
You could remove the first and last elements off the array and process them separately.
Removing all the formatting to CSS instead of inline tags would improve your code and speed up load time.
You could also avoid mixing HTML with php logic whenever possible.
Your page could be made a lot more readable and maintainable by separating things like this:
function show_subcat($val) < ?>