zakaxit zakaxit - 1 month ago 7
PHP Question

How to use modulo in tables?

How to use modulo in PHP tables?

<table border="1">
<?php for ($i = 1; $i <= 20; $i++): ?>
<?php if ($i % 5 == 0): ?>
<tr>
<?php endif ?>
<td><?php echo $i ?></td>
<?php if ($i % 5 == 0): ?>
</tr>
<?php endif ?>
<?php endfor ?>
</table>


This example show me:

1 2 3 4
5
6 7 8 9
10
11 12 13 14
15
16 17 18 19
20


I would like receive:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20


What I must use in if?

Answer

let's look at what you are doing: you start a row when $i is a multiple of five and you end a row when $i is a multiple of five. in any other case, you just print the number. so your row can only contain the value 5.

but: you want a row containing 1,2,3,4,5 - so you have to finish the row after 5, what you are doing, but start it before 1.

<table border="1">
<?php for ($i = 1; $i <= 20; $i++): ?>
    <?php if ($i % 5 == 1): ?>
        <tr>
    <?php endif ?>  
        <td><?php echo $i ?></td>
    <?php if ($i % 5 == 0): ?>
        </tr>
    <?php endif ?>  
<?php endfor ?>
</table>