Sheldon Scott
Sheldon Scott

Reputation: 741

Checking if a value is set within a PHP for loop using Laravel

Using Laravel, I want to loop through a series of grades (from '0' through '12') and, if a grade is found in my intermediate/pivot table, I want the class for that specific matching item to append 'active'.

(For example's sake, within my intermediate table, I have set it to have two active grade_ids: 6 and 7.)

I tried a for loop:

@for ($x=0; $x<=12; $x++)
    @if ($x === 0)
        <button class="circular small ui icon button">K</button>
    @else
        <button class="circular small ui icon button">{{ $x }}</button>
    @endif
@endfor

And this loops nicely through the grades from 0 (K) to 12 just fine. But then how do I make active the items that match in the DB? I need to somehow add a foreach to output the $grades as $grade (or similar) and check if $x = $grade.

But if I try an idea like that:

@for ($x=0; $x<=12; $x++)
    @if ($x === 0)
        <button class="circular small ui icon button">K</button>
    @else
        @foreach ($grades as $key=>$value)
            <button class="circular small ui icon button">{{ $value }}</button>
        @endforeach
    @endif
@endfor

the logic mucks things up by outputting K, 6, 7 with the 6, 7 being repeated 12 times. Yup, that's what I have effectively told it to do.

And doing it this way obviously doesn't work because I am only going to get a result that equals the number of rows matching in my DB:

<?php $x = 0; ?>
@foreach ($grades as $grade)
    @if ($x === 0)
        <button class="circular small ui icon button">K</button>
    @else
        <button class="circular small ui icon button">{{ $x }}</button>
    @endif
    <?php $x++; ?>
@endforeach

So, how do I output each/all of the grades (from 0 - 12) while checking if each one matches the value (grade_id) set in the intermediate database? I am guessing that this is a pretty simple task but I cannot think of what the control structure might be called that I can Google or search SO for...

[Note that I have not included the table structure as I don't think this is relevant to the question.]

Upvotes: 0

Views: 380

Answers (2)

Ali
Ali

Reputation: 3666

have the grades in a separate array and use php's in_array to check if this grade requires active or not, example:

@for ($x=0; $x<=12; $x++)
@if ($x === 0)
    <button class="circular small ui icon button">K</button>
@else
    @if in_array($x, $grades)   
        <button class="circular small ui icon button active">{{ $value }}</button>
    @else
    @endif
@endif

@endfor

Upvotes: 0

Claudio Pinto
Claudio Pinto

Reputation: 389

Try this:

@for ($x=0; $x<=12; $x++)
@if ($x === 0)
    <button class="circular small ui icon button">K</button>
@else
    <button class="circular small ui icon button {{ in_array($x, $grades)?' selected' : ''}}">{{ $x }}</button>
@endif
@endfor

modified for blade notation

Upvotes: 1

Related Questions