Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP loop split by 4

Tags:

html

loops

php

How would I achieve this PHP task?

I have an unordered html list and and array. My code adds list tags to each item in the array to create one big unordered list

            <ul>
                 <?php foreach ($rows as $id => $row): ?>
                        <li><?php print $row ?></li>
                <?php endforeach; ?>
            </ul>

current output below

            <ul>
                <li>01</li>
                <li>02</li>
                <li>.....</li>
                <li>.....</li>
                <li>15</li>
            </ul>

What I want is to split the list items so that they are in groups of 4 as sub unordered lists. If the number is not divisible by 4 then the remainder should be a smaller list at the end, for example.

            <ul>
                <ul>
                    <li>01</li>
                    <li>02</li>
                    <li>.....</li>
                    <li>.....</li>
                </ul>
                <ul>
                    <li>05</li>
                    <li>06</li>
                    <li>.....</li>
                    <li>.....</li>
                </ul>
                <ul>
                    <li>09</li>
                    <li>10</li>
                </ul>
            </ul>

Thanks in advance.

like image 660
n00b13 Avatar asked Apr 18 '26 14:04

n00b13


1 Answers

<ul>
<?php foreach ($rows as $id => $row): ?>
    <?php if ($id > 0 && $id % 4 === 0): ?>
        </ul><ul>
    <?php endif ;?>
    <li><?php echo $row; ?></li>
<?php endforeach; ?>
</ul>

(Note that if the key of your $rows array is not simply an index number, you'll need to maintain your own counter variable.)

like image 148
Tomas Creemers Avatar answered Apr 20 '26 05:04

Tomas Creemers