Getting the position (index) of an object in foreach?

Getting the position (index) of an object in foreach?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Index Trap in Laravel Foreach Loops

When you iterate over a collection using foreach, the default behavior assigns a numeric key based on the order of the items in the array. However, if your collection contains null values or empty strings, the resulting index often skips numbers or produces gaps that don't match human-readable expectations. You might see an output sequence like "1, 2, 3, 5" instead of "1, 2, 3, 4", which breaks the visual flow of lists like team standings.

In your specific case, you are attempting to display ordinal numbers for a list of teams. While str_ordinal is handy for formatting (turning "5" into "5th"), adding 1 to the raw key inside the loop doesn't solve the underlying data integrity issue. If the collection contains gaps or if the sorting logic creates sparse indices, simply incrementing the key variable yields inaccurate results.

To get the true position of the current iteration in a continuous sequence starting from one, you need to decouple the display counter from the internal array key. The most robust approach is to maintain a separate counter variable that increments on every loop cycle, regardless of what the underlying key holds.

Here is how you can refactor your Blade template to achieve a continuous count:

@php $counter = 1; @endphp

@foreach ($teams as $team)
    {{ str_ordinal($counter++) }}: {{ $team->name }}
@endforeach

By declaring $counter outside the loop and using the post-increment operator (++) within the template, you guarantee a sequential output of 1, 2, 3, 4, etc. This method works whether your collection is dense or sparse. It ensures that every team renders with the next logical number in the sequence.

Why foreach Keys Are Unreliable for Positioning

It is important to understand why relying on the default key fails here. In PHP, arrays are hash tables. When you sort a collection or filter it out of an original dense array, the internal pointer might jump. If your $teams collection was built by filtering a larger dataset and resulted in null entries being stripped, the resulting array keys will be sparse (e.g., index 0, 2, 5).

If you access count($teams) or use the key directly in this scenario, you are looking at an internal pointer value, not a visual position. The image you referenced likely shows a list where the numbering is inconsistent because the underlying data structure has gaps. Incrementing the raw key ($key + 1) simply highlights these gaps; it doesn't fill them.

Using enumerate for Cleaner Syntax

If you prefer a more functional style or are using PHP 8.2+, you can leverage the enumerate() helper to create an iterator that tracks the position automatically. This approach keeps the logic strictly inside the loop without polluting your blade template with external variables.

@foreach($teams->enumerate() as $index => $team)
    {{ str_ordinal($index + 1) }}: {{ $team->name }}
@endforeach

Note that enumerate() returns a collection where the key is always 0, 1, 2, etc., representing the iteration count. You then add 1 to align with your ordinal logic. This is particularly useful if you need to perform complex operations on the item while maintaining a clean index.

Trade-offs and Performance Considerations

When choosing between a manual counter and enumerate(), consider the source of your data. If $teams comes from an Eloquent query that has been sorted using orderBy('points', 'desc'), the resulting collection is already dense unless you explicitly filtered it in a way that removes items. If the collection is dense, the manual counter approach is marginally faster and requires zero dependencies on helper methods.

However, if your data source is dynamic or potentially sparse (containing nulls), the manual counter is safer because it abstracts away the internal state of the array entirely. The trade-off is slightly more code in your view, but it offers complete control over the numbering logic.

If you find yourself needing to map this position back into a database field later, ensure you are passing the incremented counter value rather than relying on the loop key. This distinction is crucial when syncing data or calculating rankings for API responses. For advanced ranking logic involving tie-breakers, consider using Laravel's collect with custom sorting helpers before entering the view layer.

Our network