Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

I have a simple foreach block in my view, like below.

@foreach ($teams as $key => $team) {{ str_ordinal($key + 1) }} @endforeach 

Right now I'm displaying the key, although it isn't exactly accurate. Here's an image:

enter image description here

How can I display the actual position of the current iteration? I order by my teams collection but I'm not sure how I get the position of the current interation in that loop?

like image 545
walino Avatar asked Jun 14 '18 19:06

walino


People also ask

How do I see index in forEach?

Luckily, there are several ways to get an index variable with foreach : Declare an integer variable before the loop, and then increase that one inside the loop with each loop cycle. Create a tuple that returns both the element's value and its index. Or swap the foreach loop with the for loop.

Can we get index in forEach JavaScript?

Get The Current Array Index in JavaScript forEach()forEach(function callback(v) { console. log(v); }); The first parameter to the callback is the array value. The 2nd parameter is the array index.

How do you get the index of the current iteration of a forEach loop?

by using automatic destructuring: foreach (var (value, i) in Model.

How do you find the index of a for loop?

Using enumerate() method to access index enumerate() is mostly used in for loops where it is used to get the index along with the corresponding element over the given range.


2 Answers

You can use $loop->index to get the index. Check its docs. For instance:

@foreach ($teams as  $team) {{ $loop->index }} @endforeach 

Will display 0,1,2,3,4... until the last element position.

like image 69
alynurly Avatar answered Oct 08 '22 04:10

alynurly


You can apply array_values to your data before passing to template:

array_values($teams); 

Or, according to this https://laravel.com/docs/5.6/blade#the-loop-variable, you can use special $loop variable. I suppose you need $loop->iteration property (it starts with 1) or $loop->index (starts with 0):

@foreach ($teams as $key => $team)     {{ $loop->iteration }} @endforeach 
like image 37
u_mulder Avatar answered Oct 08 '22 02:10

u_mulder