I am trying to generate a table with php for loop, that lists numbers. Something like this:
1 | 2 | 3 | 4 | 5
2 | 3 | 4 | 5 | 1
3 | 4 | 5 | 1 | 2
4 | 5 | 1 | 2 | 3
5 | 1 | 2 | 3 | 4
I still have problems getting it, this is actually quite simple, but I have not been able to solve it. 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
Thank you, any help would be appreciated!
Algorithm. Step 1: Enter a number to print table at runtime. Step 2: Read that number from keyboard. Step 3: Using for loop print number*I 10 times. // for(i=1; i<=10; i++) Step 4: Print num*I 10 times where i=0 to 10.
PHP for loop can be used to traverse set of code for the specified number of times. It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how many times you want to execute a block of code.
We can print numbers from 1 to 10 by using for loop. You can easily extend this program to print any numbers from starting from any value and ending on any value. The echo command will print the value of $i to the screen. In the next line we have used the same echo command to print one html line break.
<?php
echo "<table border='1'><br />";
for ($row = 0; $row < 5; $row ++) {
echo "<tr>";
for ($col = 0; $col < 5; $col ++) {
echo "<td>", (($col + $row) % 5) + 1, "</td>";
}
echo "</tr>";
}
echo "</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