0

I'm trying to loop through an Array, and add "active" class to first iteration only.

this is what I have tried so far but couldn't get it to work.

<?php foreach ($env_list as $key): ?>

      <?php $isFirst = true; ?>

        <li class="<?php $isFirst ? 'active' :  ?>"> <a data-toggle="tab" href="#<?php echo $key['env_name'] ?>" id="<?php echo $key['id'] ?>"> <?php echo $key['env_name'] ?></a></li>

      <?php $isFirst = false; ?>

<?php endforeach ?>

Your assistance is highly appreciated

0

3 Answers 3

4

You are setting $isFirst = true every time the loop runs. Put that line outside of the for loop so it doesn't get reset.

<?php $isFirst = true; ?>
<?php foreach ($env_list as $key): ?>
    <li class="<?php $isFirst ? 'active' :  ?>"> <a data-toggle="tab" href="#    <?php echo $key['env_name'] ?>" id="<?php echo $key['id'] ?>"> <?php echo $key['env_name'] ?></a></li>

  <?php $isFirst = false; ?>
1

If it's a numeric indexed array, you can use

foreach ($env_list as $i=>$key) and check if $i==0.

Otherwise, move your setter outside the loop. <?php $isFirst = true; ?> would need to be before the loop, otherwise it gets set each time.

1

In this code you are basically modifying that boolean on every iteration (setting it to true and then setting it back to false) twice. Try using this approach assuming you have not explicitly defined the keys of the array in question;

 <?php foreach ($env_list as $envKey => $envValue): ?>
        <li class="<?php $envKey == 0 ? 'active' :  ?>"> <a data-toggle="tab" href="#<?php echo $envValue['env_name'] ?>" id="<?php echo $envValue['id'] ?>"> <?php echo $envValue['env_name'] ?></a></li>
<?php endforeach ?>

This would check to ensure that you are dealing with the first iteration and modify it accordingly.

I trust this helps.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.