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

177
June 15, 2018, at 07:40 AM

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: https://i.imgur.com/0pvUKF5.png

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?

Answer 1

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
Answer 2

You can use $loop->index to get the index

Answer 3

Use a for loop instead of a foreach. You will get them in order.

$count = count($teams) ;
for($i=1;$i<=$count;$i++) {
    // your code here using $i as the position 
}
Rent Charter Buses Company
READ ALSO
Unknown: output handler &#39;ob_gzhandler&#39; conflicts with &#39;zlib output compression&#39; in php-phantomjs

Unknown: output handler 'ob_gzhandler' conflicts with 'zlib output compression' in php-phantomjs

i can't get any data from php-phantom it's not working with me i found this error in php_log file when i tried get source page using php-phantom and this is the Full code

228
Laravel web socket not working on production server

Laravel web socket not working on production server

I am trying to use Laravel for websocket server with orchid/socket pakageIt works fine with running following command on the local :

178
Parsing an XML response with namespaces

Parsing an XML response with namespaces

I'm getting an XML response that I cannot parseHere's the thing:

122
Array in other formate

Array in other formate

I am working on restfull api's for mobile app developmentI am returning an php array in json which is like,

179