genxweb genxweb - 4 months ago 53x
PHP Question

Nested PHP while loop to create a dynamic table that is 2 rows by 5 columns per row

My current code looks like this:

$i = 6; //will be pulled from a database
if ($i != "10") {
$countb = (10-$i);

echo "<table border=\"1\" align=\"left\">";
echo "<tr><th>Results</th>";
echo "</tr>";
while ( $i != 0) {
echo "<tr><td>";
echo "Good";
echo "</td>";
$i= $i- 1;
while ( $countb != 0) {
echo "<tr><td>";
echo "not good";
echo "</td>";
$countb= $countb- 1;
echo "</table>";

This creates a 1 column 10 row table. I want to have two rows and 5 columns per row. Basically, if the user does not have 10 good marks I want to fill in the missing goods with not good.


I think this could be simplified.

$i = 6; //will be pulled from a database
echo "<table border='1'><tr>";
for ($ix=0;$ix<10;$ix++) {

  // new row every 5 cols
  if ($ix % 5 === 0)
    echo "</tr>\n<tr>";

  // good if score less than $i
    echo "<td>Good</td>";
    echo "<td>not good</td>";
echo "</tr></table>";

Results in this output:

<table border='1'><tr></tr>
<tr><td>Good</td><td>not good</td><td>not good</td><td>not good</td><td>not good</td></tr></table>