Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

j_watson's avatar

Break foreach loop

How do I break a foreach loop after 10 times of iterations?

0 likes
8 replies
Snapey's avatar

only have 10 items?

implement a counter and increment on each loop, break after 10?

If the foreach is in blade then a $loop counter is implemented for you

j_watson's avatar

@Snapey I want to print half (not 10) of the collection on my laravel blade. I can't use limit because I also need the other half.

@foreach($list as $contestant)

	<p>{{ $contestant->name }}</p>

@endforeach
Snapey's avatar
Snapey
Best Answer
Level 122

@j_watson so much easier with code

option 1

@foreach($list->take(10) as $contestant)

	<p>{{ $contestant->name }}</p>

@endforeach

note that this does not affect your $list it will still contain 20 items

option 2

@foreach($list as $contestant)

	@if($loop->index==10) 
    @break
    @endif

	<p>{{ $contestant->name }}</p>

@endforeach

obviously not as pretty and requires testing the counter on each loop

option 3, you are doing this because you want to split 20 into two blocks of 10

@php($groups = $list->split(2))

@foreach($groups[0] as $contestant)
    	<p>{{ $contestant->name }}</p>
@endforeach

@foreach($groups[1] as $contestant)
    	<p>{{ $contestant->name }}</p>
@endforeach

j_watson's avatar

@Snapey I don't know if there's a better way but here's how I solved it. I added a counter in my controller that counts the total query results. Then I divided that result by 2. Then I passed that to my blade as the counter.

        <?php $x = 1;?>

        @foreach($contestant as $name)

              @if($x <= $counter)

                		<?php $x++;?>
               @else
                		@break
              @endif
        
        @endforeach 

Please or to participate in this conversation.