I'm making a forum in PHP. I have to display all forum categories in a table, and to do so, I have used a while loop. However, I want to have only 3 td's in every table row. To loop through the categories, I'm using a while loop with the query, so I don't think I can use modulus here.
Why can't you use modulus? Just add a counter somewhere, and if it hits % 3 == 0
reset the counter and do your stuff.
You might need to do some extra if's for first and last and stuff like that, but there is no reason not to use a modulo with a while.
$i=0;
while(guard()){
if($i % 3 == 0){
//ploing
}
$i++
}
This code will close any extra rows:
<table>
<?php
$columns = 3;
$i = 0;
while($row = mysql_fetch_array($result)){
$i++;
//if this is first value in row, create new row
if ($i % $columns == 1) {
echo "<tr>";
}
echo "<td>".$row[0]."</td>";
//if this is last value in row, end row
if ($i % $columns == 0) {
echo "</tr>";
}
}
//if the counter is not divisible by the number of columns, we have an open row
$spacercells = $columns - ($i % $columns);
if ($spacercells < $columns) {
for ($j=1; $j<=$spacercells; $j++) {
echo "<td></td>";
}
echo "</tr>";
}
?>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With