php
  1. php-table-of-number

PHP Table of Numbers

In this tutorial, we will learn how to generate a table of numbers using PHP.

Syntax

<?php
// loop through numbers
for ($i = 1; $i <= $num_rows; $i++) {
    // print table row with numbers
    echo "<tr><td>" . $i . "</td></tr>";
}
?>

Example

Let's take an example of generating a table of numbers from 1 to 10.

<!DOCTYPE html>
<html>
<head>
    <title>Table of Numbers</title>
</head>
<body>
    <table>
        <?php
            // set number of rows in table
            $num_rows = 10;

            // loop through numbers
            for ($i = 1; $i <= $num_rows; $i++) {
                // print table row with numbers
                echo "<tr><td>" . $i . "</td></tr>";
            }
        ?>
    </table>
</body>
</html>

Output

The above code will generate a table of numbers from 1 to 10 as shown below:

1
2
3
4
5
6
7
8
9
10

Explanation

In the above example, we first set the number of rows in the table to 10. We then use a for loop to loop through the numbers from 1 to 10.

For each number, we print a table row using the HTML <tr> tag and a table data cell using the HTML <td> tag. We then concatenate the number with the string using the . operator and close the table row and data cell.

Finally, we close the table using the HTML </table> tag.

Use

A table of numbers can be used in various scenarios, such as displaying student IDs, book reference numbers, or data records.

Important Points

  • We can generate a table of numbers using PHP by using a for loop and the HTML <tr> and <td> tags.
  • The number of rows in the table can be changed by setting the value of the $num_rows variable.
  • A table of numbers can be used to display various types of data in a structured format.

Summary

In this tutorial, we learned how to generate a table of numbers using PHP. We used a for loop to loop through the numbers and printed a table row and data cell for each number. A table of numbers can be used in different scenarios for displaying structured data.

Published on: