johnjay22113 johnjay22113 - 6 months ago 14
CSS Question

How to do a linebreak for every X number of boxes in a foreach loop

Here is the code:

<div>
<?php foreach($treatments as $treatment)
{ ?>
<a href="/offers/treatmentForm/<?= $treatment->treatment_name ?>">
<button class = "btn btn-info menu_button">
<div class = "treatment_box">
<p><span style="color: rgb(136, 136, 136); font-size: 20px; font-weight: bold;"><?=($treatment->treatment_name)?></span></p>
<img class = "treatment_img" src= <?= ($treatment->icon_url) ?> >
</div>
</button>
</a>
<?php } ?>

</div>


As you can see, I want to insert a linebreak after the
</a>
tag after every 4 loops. How can I do that?

Answer

Use modulus operator to check if it's your (4n)th loop:

<div>
    <?php $i = 0;
    foreach($treatments as $treatment) 
    { 
    ?>
    <a href="/offers/treatmentForm/<?= $treatment->treatment_name ?>">
    <button class = "btn btn-info menu_button">
        <div class = "treatment_box">
            <p><span style="color: rgb(136, 136, 136); font-size: 20px; font-weight: bold;"><?=($treatment->treatment_name)?></span></p>
            <img class = "treatment_img" src= <?= ($treatment->icon_url) ?> >
        </div>  
    </button>
</a>
        <?php
        if($i && ($i % 4 === 0)) {
            echo "<br/>";
        }
        $i++;
    } ?>
Comments