1

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>
Hola
  • 2,067
  • 7
  • 37
  • 81

4 Answers4

3

You should try this:

<div class="tag-area">                         
  @foreach(explode(',',$product->tags) as $key => $tag) 
      @if($key <= 5)                        
           <span>{{$tag}}</span>
      @endif
  @endforeach                       
 </div>
halfer
  • 19,471
  • 17
  • 87
  • 173
AddWeb Solution Pvt Ltd
  • 20,310
  • 5
  • 23
  • 55
1

This will help you.

<div class="tag-area">                         
      @foreach(explode(',',$product->tags) as $key => $tag) 
          @if($key <= 5)                        
               <span>{{$tag}}</span>
          @endif
      @endforeach                       
     </div>
Kashif Faraz Shamsi
  • 503
  • 1
  • 7
  • 21
  • why posting duplicate answers? Also answer is already accepted. WHat is the diif bet your answer and *AddWeb Solution Pvt Ltd* answer? – B. Desai Aug 12 '17 at 12:13
  • Same thing you have done on you previous answers also.. https://stackoverflow.com/questions/2378607/what-permission-do-i-need-to-access-internet-from-an-android-application/45650001#45650001 https://stackoverflow.com/questions/42339534/cant-answer-incoming-call-in-android-marshmallow-6-0/45649908#45649908 – B. Desai Aug 12 '17 at 12:18
0

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

B. Desai
  • 16,264
  • 5
  • 24
  • 44
0

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>
Niklesh Raut
  • 31,857
  • 10
  • 68
  • 102