Home > OS >  bootstrap 5 collapse in foreach | how to set only first element with shown
bootstrap 5 collapse in foreach | how to set only first element with shown

Time:01-26

<?php foreach ($offers as $item): ?>
<h2  id="heading<?php echo $item->id; ?>"></h2>
<div id="collapse<?php echo $item->id; ?>"  aria-labelledby="heading<?php echo $item->id; ?>" data-bs-parent="#default-accordion-example">
                  <div >
<?php echo $item->id; ?>
</div>
<?php endforeach;?>

This give me result: example 10 collapse tabs with content: 1,5,6,8,10,15,20....

issue: all collapse is opened.

I know the problem is loop:


But how to resolve and make first tab show and rest close in foreach?

CodePudding user response:

show should only be on the first element you want opened. The easiest way to keep track is to use the key, if the array doesn't have custom keys, or an iterator. Use a ternary to check for that first key, and only echo show if it's the first key.

<?php foreach ($offers as $key => $item): ?>
<h2  id="heading<?php echo $item->id; ?>"></h2>
<div id="collapse<?php echo $item->id; ?>"  aria-labelledby="heading<?php echo $item->id; ?>" data-bs-parent="#default-accordion-example">
                  <div >
<?php echo $item->id; ?>
</div>
<?php endforeach;?>
  • Related