Anonymous Girl
Anonymous Girl

Reputation: 642

How to show an item after every three elements using PHP

I am trying to show an item after every three {{ $image->title }},
but my method used creates a bit delay in loading the page, i.e. when I remove <div class='extra'>, there is reduction of 200ms.
Is there any best alternate method for below?

@foreach( $images as $index =>$image)  
 <div>
   {{ $image->title }}
 </div>
  @if( count($images) > 0 && $index != 0 && ($index % 3) == 0 )
    <div class="extra">
      Item to show after three Image Titles
    </div>
  @endif    
@endforeach

Upvotes: 1

Views: 85

Answers (1)

dz0nika
dz0nika

Reputation: 1021

Laravel has its own Blade $loop variable that is meant to help you with this check out the docs here https://laravel.com/docs/8.x/blade#loops

In your case something like this makes more sense

 @foreach( $images as $index =>$image)  
 <div>
   {{ $image->title }}
 </div>
  @if( $loop->iteration % 3) // this can be $loop->index but im not sure what you need
    <div class="extra">
      Item to show after three Image Titles
    </div>
  @endif    
@endforeach

Upvotes: 3

Related Questions