Skip to content
Advertisement

Get the first element in a for loop with php [closed]

How can i add the active class only, just to the first element in this for loop?

for($i = 0; $i < $akcios_kepek_num; $i++)
{
  if($i == 1 ){
    $active = "active";
  }else{
    $active = "";
      }

   echo '<li data-target="#carousel-example-3" data-slide-to="'.$i.'" class="'.$active.'"></li>';

}

I tryed to check it, with the $i == 1 code, but it will add the active class to all the elemtnts.

Advertisement

Answer

Something like that should works. First element is $i == 0 and I used ternary operator to replace if/else is little more elegant

for($i = 0; $i < $akcios_kepek_num; $i++)
{
   $active = $i == 0 ? "active" : "";
   echo '<li data-target="#carousel-example-3" data-slide-to="'.$i.'" class="'.$active.'"></li>';
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement