0

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 class="nav-item active".

<ul class="nav nav-pills nav-fill" id="pills-tab" role="tablist">
    <?php foreach($content['tabs'] as $tab){ echo 
       '<li class="nav-item" role="presentation">
           <button class="nav-link" 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 class="h4">'.$tab["label"].'</h2>
           </button>
        </li>';
     } ?>
</ul>

1 Answer 1

2

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 class="nav nav-pills nav-fill" id="pills-tab" role="tablist">
<?php $i = 1; foreach($content['tabs'] as $tab){ echo 
   '<li class="nav-item ' . ($i == 1 ? "active" : "") . '" role="presentation">
       <button class="nav-link" 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 class="h4">'.$tab["label"].'</h2>
       </button>
    </li>';
$i++; 
} ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Or just replace $i++ with $i=0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.