Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Loop Table in PHP

Tags:

php

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!

like image 366
Afnizar Nur Ghifari Avatar asked Apr 01 '14 13:04

Afnizar Nur Ghifari


People also ask

How do I make a loop table?

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.

Can we use for loop in PHP?

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.

How can I print 1 to 10 numbers in PHP?

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.


1 Answers

<?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>";
?>
like image 191
remudada Avatar answered Sep 28 '22 03:09

remudada