Home > database >  How to exclude items in foreach loop
How to exclude items in foreach loop

Time:04-14

I'm trying to display a specific set of references on my laravel page by iterating through an foreach loop and styling odd and even iterations differently with @class loop odd / loop even.

However I as I begin the foreach loop with an @if, only some make it into the loop while some are skipped, which messes up my odd / even (e.g. #1, #2 and #4 make it into the loop which means I have two elements styled with loop even.

How can I skip the ones that don't make it into the loop so I can display the result with alternating styling?

@foreach ($references as $reference )
    @if(isset($reference['is_startpage']) 
        && $reference['is_startpage'] != 1 
        && isset($reference['content']['featured']) 
        && $reference['content']['featured'] == 1)

        <div @class([
                    'row py-5' => $loop->odd,
                    'row flex-row-reverse py-5'=> $loop->even,
                    ])></div>
    @endif
@endforeach

CodePudding user response:

As you say, not every loop iteration prints the <div> element, so $loop->even and $loop->odd variables are not valid in your case for implementing that specific logic. However, there are many ways to achieve what you want. The first way that comes into my mind is using a specific counter for that, i.e.:

@php $featuredCount = 0; @endphp
@foreach ($references as $reference)
    @if(
        isset($reference['is_startpage']) 
        && $reference['is_startpage'] != 1 
        && isset($reference['content']['featured']) 
        && $reference['content']['featured'] == 1
    )
        @php $featuredCount  ; @endphp
        <div @class([
             'row py-5', // These two are always present, no need to conditionally rewrite them
             'flex-row-reverse' => $featuredCount % 2 == 0, // 'Even' check
        ])></div>
    @endif
@endforeach
  • Related