PHP program for factorial

The factorial function (symbol: !) says to multiply all whole numbers from our chosen number down to 1.

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

So maths rules is n! = n × (n−1)!

Factorial of 0 is always 1.

How to Find Factorial in PHP?

There are two ways to find factorial in PHP as below.

1. Using Loop : We will use for loop to iterate over the sequence of numbers to get the factorial.
2. Using recursive method : We will call the same method to get the sequence of the factorial.

Lets see below example to find factorial  for number using form in php.




Example :

function find_factorial($number){
if($number <= 1){
return 1;
return $number * find_factorial($number - 1);



// PHP code to get factorial using method recursion

$fact_num = find_factorial($num);
$result .= "<br/>Factorial Number for $num! using recursion method is $fact_num";

// PHP code to get the factorial of a number using for loop
for ($i = 1; $i <= $num; $i++){
$factorial = $factorial * $i;

$result .= "<br/>Factorial Number for $num! using loop is $fact_num";


<!DOCTYPE html>
<title>PHP Maths Program - Find factorial by aryatechno</title>
<form name="find" method="post">
<td colspan="2"><strong>Find factorial program</strong></td>
<td>Enter Number :</td>
<td><input type="text" name="num" value="<?=$_POST['num'] ?>" required></td>

<td><input type="submit" value="Find factorial" name="submit" /></td>
<td colspan="2"><strong><?=$result ?></strong></td>


Output :


Leave a Reply

Your email address will not be published. Required fields are marked *