Factorial program in PHP
In this program, you will find factorial of number by using loop.
i) for loop
ii) while loop
iii) do while loop
2) using recursive function
3) using HTML form
factorial of a number is the multiplication of all its below number.
for example: 5! = 5*4*3*2*1 = 120
Factorial program in PHP using for loop
In this program factorial of 5 using the for loop program is shown:
<?php
$n=5;
$fact=1;
for($i=1;$i<=$n;$i++){
$fact=$fact*$i;
}
echo "factorial of 5 is: $fact";
?>
output
factorial of 5 is: 120
Factorial program in PHP using while loop
In this program factorial of 6 using the while loop program is shown:
<?php
$n=6;
$fact=1;
$i=1;
while($i<=$n){
$fact=$fact*$i;
$i++;
}
echo "factorial of 6 is: $fact";
?>
output
factorial of 6 is: 720
Factorial program in PHP using do while loop
In this program factorial of 4 using do while loop program is shown:
<?php
$n=4;
$fact=1;
$i=1;
do{
$fact=$fact*$i;
$i++;
}while($i<=$n);
echo "factorial of 4 is: $fact";
?>
output
factorial of 4 is: 24
Factorial program in PHP using recursion
In this program factorial of 5 using the recursive method program is shown:
<?php
function factorial($n)
{
if($n>1)
{
return $n*factorial($n-1);
}
else{
return 1;
}
}
echo "factorial of 5 is:".factorial(5);
?>
output
factorial of 5 is:120
Factorial program using HTML form in PHP
<!DOCTYPE html>
<html lang="en">
<head>
<title>factorial program</title>
</head>
<body>
<form>
Enter the number <input type="number" name="factorial">
<input type="submit" value="submit" name="click"></br>
</form>
</body>
</html>
<?php
if(isset($_GET["click"]))
{
$n=$_GET['factorial'];
$fact=1;
$i=1;
while($i<=$n){
$fact=$fact*$i;
$i++;
}
echo "factorial of $n is: $fact";
}
?>