I am running a for loop grabbing data from a database and I want to create a new row every time I create 4 table datas, how could I go by doing this?
example:
<table>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
</table>
Use Modular arithmetic: http://snook.ca/archives/php/the_modulo_oper
(not my site, I googled it for this gentleman.)
Something like that should do the trick.
$i = 0;
echo "<table><tr>";
while ($i < 50) {
echo "<td></td>";
if ($i % 4 == 0) {
echo "</tr><tr>";
}
$i++;
}
echo "</tr></table>";
I let you handle as a homework the case where you end width a $i%4 == 0
so you end the code with </tr><tr></tr></table>
<table>
<tr>
<?php
$i = 0;
foreach ($data as $item)
{
echo "<td>$item</td>";
$i++;
if ($i % 4 == 0)
{
echo "</tr>
<tr>";
}
}
// if total count of $data is not divisible with 4,
// we have to complete the last row with empty cells
for ($j = 0; $j < (4 - ($i % 4)); $j++)
{
echo "<td> </td>";
}
?>
</tr>
</table>