Insert tr after every third loop

I am making a forum in PHP. I have to display all forum categories in a table, and for this I used a while loop. However, I want to have only 3 td in each row of the table. To scroll through the categories, I use a while loop with a query, so I don't think I can use the module here.

+7
source share
3 answers

Why can't you use the module? Just add a counter somewhere, and if it goes to % 3 == 0 reset the counter and does your stuff.

You may need to do something else if for the first and last and the like, but there is no reason not to use the time modulo.

 $i=0; while(guard()){ if($i % 3 == 0){ //ploing } $i++ } 
+13
source

This code will close any additional lines:

 <table> <?php $i = 0; while($row = mysql_fetch_array($result)){ $i++; //if this is first value in row, create new row if ($i % 3 == 1) { echo "<tr>"; } echo "<td>".$row[0]."</td>"; //if this is third value in row, end row if ($i % 3 == 0) { echo "</tr>"; } } //if the counter is not divisible by 3, we have an open row $spacercells = 3 - ($i % 3); if ($spacercells < 3) { for ($j=1; $j<=$spacercells; $j++) { echo "<td></td>"; } echo "</tr>"; } ?> </table> 
+11
source

I have not 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> 
+2
source

All Articles