Avatar ·

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

Hello, colleagues! I'm a beginner in PHP and encountered this situation: I have an array of products, and I'm outputting them using foreach. I need the first element to be displayed with the class "first" and the last element with the class "last". But I don't know how to determine which iteration we're on inside the loop. Here's an example of my code: ```php $product
"; } ?> ``` I know that some languages have iteration counters, but in PHP I can't figure out how to do this without additional variables. I tried using `current()` and `end()`, but they only work with the internal array pointer, which gets messed up inside the for loop.

No answers yet.

Log in to leave an answer

Blogs