Afnizar Nur Ghifari
Afnizar Nur Ghifari

Reputation: 144

Make table with for loop

Basically, I am just trying to learn how to generate a table with PHP for loop that lists numbers in sequential order. Something like this:

21 | 26 | 31 | 36 
22 | 27 | 32 | 37
23 | 28 | 33 | 38
24 | 29 | 34 | 39
25 | 30 | 35 | 40

I know this is probably very simple, but I can't seem to figure it out! So far I have the following code:

<?php
echo "<table border='1'><br />";

for ($row = 0; $row < 5; $row ++) {
   echo "<tr>";

   for ($col = 1; $col <= 4; $col ++) {
        echo "<td>", ($col + ($row * 4)), "</td>";
   }

   echo "</tr>";
}

echo "</table>";
?>

However, this only generates the following:

1  | 2  | 3  | 4 
5  | 6  | 7  | 8
9  | 10 | 11 | 12
13 | 14 | 15 | 16
17 | 18 | 19 | 20

I'm trying to generate a table with 4 rows and 5 columns. Any help would be greatly appreciated!

Upvotes: 0

Views: 104

Answers (2)

m-farhan
m-farhan

Reputation: 1426

<?php
echo "<table border='1'><br />";

for ($row = 21; $row <=25; $row ++) {
   echo "<tr>";
   $x=$row;
   for ($col = 1; $col <= 4; $col ++) {
        echo "<td>".$x. "</td>";
        $x+=5;
   }

   echo "</tr>";
}

echo "</table>";
?>

Upvotes: 1

hindmost
hindmost

Reputation: 7195

$start = 21;
$n_rows = 5;
$n_cols = 4;

$out = '';
for ($i = 0; $i < $n_rows; $i++) {
    $row = '';
    for ($j = 0; $j < $n_cols; $j++) {
        $row .= '<td>'. ($start + $i + ($j * $n_rows)). '</td>';
    }
    $out .= '<tr>'. $row. '</tr>';
}
$out = '<table border="1">'. $out. '</table>';
echo $out;

Upvotes: 2

Related Questions