skip to Main Content

I’m using a while loop to populate tabs with PHP. If I assign active while it’s in the loop then they are all active. This much I understand. If I only want the first item / tab to have the class="tab-pane fade p-2 –>active<–" where should the script be changed?

while($row  = $result->fetch_assoc() ) {
  $id = $row['id'];
  $in = $row['initial'];
  $name = $row['name'];     
echo "<div class="tab-pane fade p-2 active" id="$in" role="tabpanel" aria-labelledby="$in-tab">"; // make tabs

2

Answers


  1. Track an indicator that you’ve already rendered the "first" tab. Something as simple as:

    $firstTab = true;
    

    Then within the loop, set it to true after rendering the "first" tab, conditionally including the active class:

    $firstTab = true;
    while($row  = $result->fetch_assoc() ) {
      $id = $row['id'];
      $in = $row['initial'];
      $name = $row['name'];     
      echo "<div class="tab-pane fade p-2 " . ($firstTab ? "active" : "") . "" id="$in" role="tabpanel" aria-labelledby="$in-tab">";
      $firstTab = false;
    }
    
    Login or Signup to reply.
  2. First: write HTML as HTML, not using strings.

    You’ll need to use a index, like:

    <?php
    $i = 0;
    
    while($row  = $result->fetch_assoc() ) {
      $id = $row['id'];
      $in = $row['initial'];
      $name = $row['name'];
    ?>
    <div class="tab-pane fade p-2 <?= $i === 0 ? 'active' : '' ?>" id="<?= $in ?>" role="tabpanel" aria-labelledby="<?= $in-tab ?>">
    ...
    </div>
    <?php
      $i++;
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search