Insert tr after every third loop

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.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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++
}

Solution 2

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>

Solution 3

I haven’t tested the code, but the logic should work:

<Table>
<?php
$i = 0;
while($row = mysql_fetch_array($result)){
    if($i == 0){
        echo"<TR>";
    }
    echo"<td>".$row[0]."<TD>";
    $i++;
    if($i == 3)
    {
        $i = 0;
        echo"</tr>"
    }
}
if($i ==1){
    echo "<td></td><td></td></tr>";
}
if($i ==2)
{
    echo "<td></td></tr>";
}
?>
<table>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply