How to calculate factorial in php | Factorial program in php | factorial recursion

The factorial of a number is the product of all integers up to and including that number, so the factorial of 5 is 120.

Example

4! = 4*3*2*1 = 24  
5! = 5*4*3*2*1 = 120 

Points to be noted.

  • It is denoted by n! and is calculated only for positive integers.
  • Factorial of 0 is always 1
  • The simplest way to find the factorial of a number is by using a loop or Using recursive method

factorial program in php using for loop

<?php
$num = 5;
$fact = 1;
for($i = 1; $i <=$num;$i++) // initially, i = 1
{
	$fact = $fact * $i; // 
}
echo "factorial of $num is = ".$fact;
?>

Note : Above code will be iterate : 1 * 2* 3* 4* 5 = 120

Factorial of number 5
Factorial of number 5

Factorial in PHP

<?php
$num = 7;
$fact = 1;
for($i = $num; $i >= 1; $i--) // intiallly, i = 7
{
	$fact = $fact * $i; // 
}
echo "factorial of $num is = ".$fact;
?>

Note : Above code will be iterate : 7*6*5 * 4* 3* 2* 1 = 5040

Factorial in PHP
Factorial in PHP

factorial program in php using recursion | factorial recursion

<?php
function getFactorialofNumber($number){ 
    if($number <= 1){   
        return 1;   
    }   
    else{   
        return $number * getFactorialofNumber($number - 1);   
    }   
} 

echo "factorial of 6 is = ".getFactorialofNumber(6);
?>
factorial recursion
factorial recursion

Pradip Mehta

I am a well-organized professional in Drupal Development and PHP web development with strong script handling knowledge or automation process with PHP. I have advanced computer skills and am a proficient multitasker.