Php program to find a factorial of given number

The factorial of a number n is defined by the product of all the digits from 1 to n (including 1 and n). Here we write program, how to print factorial of any number in php. For Example: 5! = 5*4*3*2*1 = 120 Factorial of 0 is always 1 There are 2 ways to find factorial of given number 1. by using loop 2. by using recursive method.

Factorial of a number using Loop
$num = 5;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
##########################
OUTPUT:
Factorial of 5 is 120
#####################
Factorial of a number using recursive function
function fact ($n)
{
 if($n <= 1)
 {
 return 1;
 }
 else
 {
 return $n * fact($n - 1);
 }
}
echo "Factorial of 5 is " .fact(5);
?>
###############################
OUTPUT:
Factorial of 5 is 120
#########################

Leave a Reply