% - module operator. It returns the remainder after division, so 7 % 4 == 3 .
You really need to start at 0. This is because 0 % 4 == 0 and 4 % 4 == 0 ... And you want the first element to be a new line! So you want newlines at 0, 4, 8, etc. If you start with one, then 1, 2, and 3 will not be on the line.
In addition, we must remember to close the line for each item to a new line.
Finally, if we exit our loop without closing the last line, we must do so after exiting the loop.
I will show how to do this with tables, but you can use divs with classes just as easily.
<table> <?php // Start at zero, so we start with a new row // Since we start at 0, we have to use < number of items, not <= for ($i = 0; $i < $numberOfItems; ++$i) { // if divisible by 0 start new row if ($i % 4 == 0) echo '<tr>'; // Always print out the current item echo '<td>' . $item[$i] . '</td>'; // If the next $i is divisible by 4, we have to close the row if ($i % 4 == 3) echo '</tr>'; } // If we didn't end on a row close, make sure to close the row if ($i % 4 != 3) echo '</tr>'; ?> </table>
source share