Home > Blockchain >  How to get the last item of for loop
How to get the last item of for loop

Time:11-14

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?

CodePudding user response:

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
    }
}
  • Related