Roel
Roel

Reputation: 1472

PHP end div after X amount of divs and start new one

I am trying to achieve to show 4 divs on 1 line and after those 4 divs it should automatically end the line and continue with the new line of 4 divs. What I have right now is;

            <?php
            // Make sure to just show items if there are any.
            if ($is_empty)
            {
                echo 'There are no products found.';
            }
            else
            {
                // Start counting the products.
                $i = 1;

                // List up all products.
                foreach ($results as $item):
                    // Count up the productcount.
                    $i++;
        ?>
                            <a href="<?php echo base_url(); ?>product/<?php echo $item['product_id']."-".$item['name_clean']; ?>.html">
                                <?php echo $item['name']; ?>
                            </a>
        <?php
                endforeach;
            }
        ?>

So like, if $i = 4, 8, 12 etc etc, cut off the line (maybe add a div that's holding those 4?) and start a new one. Is that possible? I know it is with tables, as I found here PHP: End and start a new <tr> after 6 rows

Thanks.

Upvotes: 0

Views: 587

Answers (1)

Konrad Dzwinel
Konrad Dzwinel

Reputation: 37903

Use modulus (%) to calculate every 4th element.

    <?php
            // Start counting the products.
            $i = 0;

            // List up all products.
            foreach ($results as $item):
                // Count up the productcount.
                $i++;
    ?>
                        <a href="<?php echo base_url(); ?>product/<?php echo $item['product_id']."-".$item['name_clean']; ?>.html">
                            <?php echo $item['name']; ?>
                        </a>
    <?php
                if($i%4 == 0):
    ?>
                        <br />
    <?php  
                endif;
    ?>
            endforeach;
    ?>

Upvotes: 4

Related Questions