Reputation: 2233
There may be 5 or 6 values inside the foreach loop but i need to print suppose first 5 or 6 values.How do i do that?
<div class="tag-area">
@foreach(explode(',',$product->tags) as $tag)
<span>{{$tag}}</span>
@endforeach
</div>
Upvotes: 1
Views: 1561
Reputation: 21681
You should try this:
<div class="tag-area">
@foreach(explode(',',$product->tags) as $key => $tag)
@if($key <= 5)
<span>{{$tag}}</span>
@endif
@endforeach
</div>
Upvotes: 3
Reputation: 511
This will help you.
<div class="tag-area">
@foreach(explode(',',$product->tags) as $key => $tag)
@if($key <= 5)
<span>{{$tag}}</span>
@endif
@endforeach
</div>
Upvotes: 1
Reputation: 34914
if you have 10 element in array no need to iterate after 4 iteration so you should break foreach iteration
<div class="tag-area">
@foreach(explode(',',$product->tags) as $key=>$tag)
@if($key >= 4)
@break
@endif
<span>{{$tag}}</span>
@endforeach
</div>
Upvotes: 0
Reputation: 16436
If your key is numenric and its of indexed array you can directly do it like:
<div class="tag-area">
@foreach(explode(',',$product->tags) as $key => $tag)
@if($key <= 5)
<span>{{$tag}}</span>
@else
<?php break; ?>
@endif
@endforeach
OR try this;
<div class="tag-area">
<?php $cnt == 0; ?>
@foreach(explode(',',$product->tags) as $tag)
<span>{{$tag}}</span>
<?php
$cnt++;
if($cnt >= 5)
break;
?>
@endforeach
Remember break;
will stop unnecessary execution of loop
Upvotes: 0