In this tutorial, we will learn how to write factorial programs in PHP using for loop and recursion functions.
Factorial says to multiply all numbers from the chosen number to 1. The factorial symbol is “!”
For examples:
4! = 4 × 3 × 2 × 1 = 24
7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
Factorial Program in PHP
There are two methods to calculate the factorial of any number:
- Using loop
- factorial program in PHP using loop
- factorial program in PHP using the form
- Using recursive method
- factorial program in PHP using recursion
#Using loop
Factorial program in PHP using loop
Here we will create a PHP program to find or calculate factorial of number 5 using the for loop in PHP.
<?php // define variable and assign value, which you want to find factorial $num = 5; //define variable, which you want to store factorial number value $factorial = 1; //iterate the loop for ($i=1; $i <= $num; $i++) { $factorial = $factorial * $x; } // display the factorial of number echo "Factorial of $num is $factorial"; ?>
Factorial program in PHP using the form
Here we will create a PHP program to find or calculate the factorial of any number using PHP form.
<html> <head> <title>Factorial using Form in PHP</title> </head> <body> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> Enter the Number:<br> <input type="number" name="number" id="number"> <input type="submit" name="submit" value="Submit" /> </form> <?php if($_POST){ $fact = 1; //getting value from input text box $number = $_POST['number']; echo "Factorial of $number:<br><br>"; //start loop for ($i = 1; $i <= $number; $i++){ $fact = $fact * $i; } echo $fact . "<br>"; } ?> </body> </html>
#Using recursive method
factorial program in PHP using recursion
Here we will create a PHP program to find or calculate factorial of any number using the recursion in PHP.
<?php function factorial($n) { if($n <= 1) { return 1; } else { return $n * factorial($n - 1); } } echo "Factorial of 6 is " .factorial(6); ?>