Hola
Hola

Reputation: 2233

How to print only 4 values inside foreach loop?

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

Answers (4)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

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

Kashif Faraz Shamsi
Kashif Faraz Shamsi

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

Niklesh Raut
Niklesh Raut

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

B. Desai
B. Desai

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

Related Questions