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:
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?
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.
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.
by using automatic destructuring: foreach (var (value, i) in Model.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With