简体   繁体   中英

Print class inside echo once in foreach and ignore in other loops

i have foreach like this

EDIT

foreach ($lists as $list) {
    echo '<li class="">'. $list .'</li>';
}

how i can add active to first li class once like this class="active" and other loops show with empy class "default"

💘💙 thank you all for helping 💙💘

You could do something like this

$active = false;
foreach($lists as $list){
    echo '<li class="'.(!$active ? 'active' : '').'">'. $list .'</li>';
    $active = true;
}

Try this

$counter = 0;
foeach($lists as $list){
if($counter==0)
 echo '<li class="active">'. $list .'</li>';
else
 echo '<li class="">'. $list .'</li>';
   $counter++;
}

If you want to set active to first <li> element, then you can do like this.

foeach($lists as $key => $list){
       if($key == 0){
           echo '<li class="active">'. $list .'</li>';
       }else{
        echo '<li class="">'. $list .'</li>';
      }
}

If you are using Laravel 5.3 or higher you can use this

@foreach($lists as $list)
<li @if($loop->iteration == 1) class="active" @endif>{{ $list }}</li>
@endforeach

You have to impose some kind of condition on value or index of array. Suppose we have to put active class on first element

// track array by its index and first element has index 0
foreach($list as $index => $list)
{
   // if index is 0 then put active class to list with ternary condition
   echo '<li class="'.(($index==0)?'active':'').'">'. $list.'</li>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM