Reputation: 201
So in Laravel, when we use foreach
loop, we can simply say:
@foreach ($colors as $k => $v)
@if($loop->last)
// at last loop, code here
@endif
@endforeach
To get the last item of the loop.
But what if we use for
loop like this:
@for($y=0;$y<=count($paths)-1;$y++)
// if last item of the loop, do something here
@endfor
So how I define the last item of for
loop just like foreach
loop?
Upvotes: 1
Views: 1837
Reputation: 1076
You can use array functions just like end()
and/or current()
and/or ect .
for ex :
foreach ($colors as $k => $v) {
if($v == end($colors)) {
// at last loop, code here
}
}
also can try to keep iterates number and check if is it the last one or not, but the first solution has better performance and keeps your code cleaner.
$iterateNumber = 0;
foreach ($colors as $k => $v) {
$iterateNumber++ ;
if($iterateNumber == count($colors)) {
// at last loop, code here
}
}
Upvotes: 1