Search code examples
phplaravelfor-loopforeachlaravel-blade

Can I return different values ​with for in foreach?


Every time the foreach returns, it writes the element with values[0] because $i=0. I want foreach to print values[0] when it returns first and values[1] when it returns second. Where exactly should I do the for loop?

@foreach ($videohistories as $videohistory)
                <tr>
                    <td>{{ date("Y-m-d H:i:s", $videohistory->create_time) }}</td>
                    <td>{{ date("Y-m-d H:i:s", $videohistory->end_time) }}</td>
                    <td>{{ diff_date_format($videohistory->begin_time, $videohistory->end_time, "%H sa %i dk. %s sn") }}</td>
                    <td>
                        @for($i = 0; $i < $values; $i++) {{$values[$i]}} @break @endfor </td>
                </tr>
                @endforeach

Solution

  • You are doing a for loop in each iteration and then breaking out at the first iteration of that loop. If you want to print the i-th element based on the foreach iteration you need to use the $loop variable

    @foreach ($videohistories as $videohistory)
         <tr>
             <td>{{ date("Y-m-d H:i:s", $videohistory->create_time) }}</td>
             <td>{{ date("Y-m-d H:i:s", $videohistory->end_time) }}</td>
             <td>{{ diff_date_format($videohistory->begin_time, $videohistory->end_time, "%H sa %i dk. %s sn") }}</td>
             <td>
                 @if (isset($values[$loop->index])) 
                     {{$values[$loop->index]}}
                 @endif
             </td>
        </tr>
    @endforeach