Home > Blockchain >  Add unique css class to first iteration of foreach php loop
Add unique css class to first iteration of foreach php loop

Time:07-24

Beginner's question. I have a working foreach loop using bootstrap for styling and tab navigation. I need to declare the class of ONLY the first tab (iteration) as "active" as in .

<ul  id="pills-tab" role="tablist">
    <?php foreach($content['tabs'] as $tab){ echo 
       '<li  role="presentation">
           <button  id="pills-'.$tab["label"].'-tab" 
           data-bs-toggle="pill" data-bs-target="#pills-'.$tab["label"].'" 
           type="button" role="tab" aria-controls="pills-'.$tab["label"].'" 
            aria-selected="true">
           <h2 >'.$tab["label"].'</h2>
           </button>
        </li>';
     } ?>
</ul>

CodePudding user response:

You can set a variable to have a value of 1 and increment it with each iteration of the foreach loop. Once you have that you can check if the current iteration is equal to 1.

<ul  id="pills-tab" role="tablist">
<?php $i = 1; foreach($content['tabs'] as $tab){ echo 
   '<li active" : "") . '" role="presentation">
       <button  id="pills-'.$tab["label"].'-tab" 
       data-bs-toggle="pill" data-bs-target="#pills-'.$tab["label"].'" 
       type="button" role="tab" aria-controls="pills-'.$tab["label"].'" 
        aria-selected="true">
       <h2 >'.$tab["label"].'</h2>
       </button>
    </li>';
$i  ; 
} ?>
  •  Tags:  
  • php
  • Related