Multiplication Table in PHP using For loop | While loop | Function
Multiplication table in PHP using for loop, while loop, and function.
In this article, you will learn how to make a multiplication table in PHP using for loop, while loop, and function.
Example
----The input number is: 17
----The range number is: 11
----The above multiplication table--------
17 * 1 = 17
17 * 2 = 34
17 * 3 = 51
17 * 4 = 68
17 * 5 = 85
17 * 6 = 102
17 * 7 = 119
17 * 8 = 136
17 * 9 = 153
17 * 10 = 170
17 * 11 = 187
You should have the knowledge of the following topics in PHP programming to understand these programs:
- PHP
while
loop - PHP
For
loop - PHP Functions
In this article, we solve this problem in three methods:
Source Code
<?php
// Multiplication table in PHP using While loop
$x = 17;
$r = 11;
echo "----The input number is: ", $x, "\n";
echo "\n----The range number is: ", $r, "\n";
// $x - To store the input number
// $r - To store the multiplication range
echo "\n\n----The above multiplication table--------\n\n";
$i = 1;
while ($i <= $r) {
echo "\t", $x, " * ", $i, " = ", $x * $i, "\n";
$i++;
}
?>
Output
----The input number is: 17
----The range number is: 11
----The above multiplication table--------
17 * 1 = 17
17 * 2 = 34
17 * 3 = 51
17 * 4 = 68
17 * 5 = 85
17 * 6 = 102
17 * 7 = 119
17 * 8 = 136
17 * 9 = 153
17 * 10 = 170
17 * 11 = 187
Explanation
In this given program, we have stored two values 17
for input value and 11
for a range of the multiplication size.
Then we applied simple multiplication using the while loop on these inputs, Then this will print the complete multiplication.
Multiplication Table in PHP using For loop
<?php
// Multiplication table in PHP using For loop
$x = 17;
$r = 11;
echo "----The input number is: ", $x, "\n";
echo "\n----The range number is: ", $r, "\n";
// $x - To store the input number
// $r - To store the multiplication range
echo "\n\n----The above multiplication table--------\n\n";
for ($i = 1; $i <= $r; $i++) {
echo "\t", $x, " * ", $i, " = ", $x * $i, "\n";
}
?>
Multiplication Table in PHP using Function
<?php
// Multiplication table in PHP using Function
$x = 15;
$r = 12;
echo "----The input number is: ", $x, "\n";
echo "\n----The range number is: ", $r, "\n";
// $x - To store the input number
// $r - To store the multiplication range
MultiplicationTable($x, $r);
// This function will print the multiplication table
function MultiplicationTable($x, $y) {
echo "\n----The above multiplication table--------\n\n";
$i = 1;
while ($i <= $y) {
echo "\t", $x, " * ", $i, " = ", $x * $i, "\n";
$i++;
}
}
?>
Output
----The input number is: 15
----The range number is: 12
----The above multiplication table--------
15 * 1 = 15
15 * 2 = 30
15 * 3 = 45
15 * 4 = 60
15 * 5 = 75
15 * 6 = 90
15 * 7 = 105
15 * 8 = 120
15 * 9 = 135
15 * 10 = 150
15 * 11 = 165
15 * 12 = 180