PHP Program to Program to print multiplication table of any number using HTML forms


October 23, 2023, Learn eTutorial
452

In this PHP program, we can see how to print a multiplication table of a given number.

Here we are using HTML and PHP to generate this multiplication table. We use the HTML code for designing the form to get the input from the user, and the PHP code is used to perform the multiplication and display the multiplication table.

Form Generation in PHP using HTML code

For this program, we need a textbox to input the number and a button to perform the calculations.


<form method="POST">
   Enter a number:  
   <input type="text" name="number">
   <input type="Submit"value="Generate Multiplication Table">
</form>
 

Inside the PHP form, we are using the post method, the user has to enter the number and press the submit button to enter the input to the form.


<?php 
if($_POST) { 
    $num = $_POST["number"]; 
       echo nl2br("<p  center;'>
        Multiplication Table of $num: </p>
    "); 
          
    for ($i = 1; $i <= 10; $i++) {          echo ("<p  center;'>$num"
            . " X " . "$i" . " = " 
            . $num * $i . "</p>
        "); 
    } 
} 
?>
 

When the user submits the form the value will be passed to the $num variable and we will generate the multiplication table depending on the user input. Finally, we will display the multiplication table. 

How to generate a multiplication table in PHP?

Step 1: Accept the input from the user and store it in the variable $num

Step 2: Using a for loop with condition i <= 10 do the following step (i) incrementing the value of variable i in every iteration

        (i) Print the result of num x i using echo as the multiplication of the entered number

Here is the full code for the multiplication table program.

PHP Source Code

                                          
<!DOCTYPE html>
<html>
  
<body>
    <center>         <h1 >
            Learn eTutorials : PHP Multiplication Table
        </h1>
  
  
        <form method="POST">
            Enter a number:  
            <input type="text" name="number">
              
            <input type="Submit" 
                value="Get Multiplication Table">
        </form>
    </center>
</body>
  
</html>
  
<?php 
if($_POST) { 
    $num = $_POST["number"]; 
       echo nl2br("<p >
        Multiplication Table of $num: </p>
    "); 
          
    for ($i = 1; $i <= 10; $i++) {          echo ("<p >$num"
            . " X " . "$i" . " = " 
            . $num * $i . "</p>
        "); 
    } 
} 
?>
                                      

OUTPUT

PHP: Multiplication Table