Bruce Bruce - 1 month ago 10
PHP Question

laravel blade for and foreach with if loop maximum time

I want to for loop 7,and foeach $time to blade.

if has $time foreach = for loop $i is output

<div>O</div>
, else is output
<div>X</div>


but my code is trouble... loop 35 time.

I want loop total maximum time of 7 times

if $time = [3,6]

example output :X X X O X X O


or if $time = [ 1 , 2 , 4]

example output : X O O X O X X


How can I do, Please help me, thanks~

blade.php

@for ($i = 0; $i < 7; $i++)
@foreach($time as $value)

@if($value->time == $i)
<div>O</div>
@else
<div>X</div>
@endif

@endforeach
@endfor


Controller

public function interview()
{
$time = Interview_time::where('bsinformations_id',5)->get();
return view('bs_sidebar.interview_time', [
'time' => $time
]);
}

Answer

You can try this way:

@for ($i = 0; $i < 7; $i++)
    $check = 0;
    @foreach($time as $value)

        @if($value->time == $i)
            <?php
                $check = 1;
            ?>
            @break 
        @endif

    @endforeach
    @if $check == 1
        <div>O</div>
    @else
        <div>X</div>
    @endif
@endfor

so this way, the loop will only run 7 times,

please give it a try and let me know if it helps you

Thanks.