Factorial of a Number using PHP

Current factorial example

The factorial of a non-negative integer is the product of every positive integer up to that number. By definition, 0! is 1.

<?php
$number = 5;
$factorial = 1;

for ($i = 2; $i <= $number; $i++) {
    $factorial *= $i;
}

echo $number . '! = ' . $factorial;
?>

For form input, validate that the value is an integer and reject negative numbers before calculating the factorial.

Factorial of a number is product of all integers from 1 up to the number ( inclusive ).
Factorial of 5 is 1*2*3*4*5 = 120
Or
n! = 1*2*3….n

Factorial using looping

$n1=50; // change this number
for($i=1;$i<=($n1/2); $i++){
	if($n1%$i == 0 )
		echo " $i," ;
}
echo  $n1 ;
Factorial of an input number through sticky form in PHP using for loop or using recursive function

Using for loop

More details on for loop in PHP.
$n1=5; // change this number 
$factorial=1;
for ($i=1; $i<=$n1;$i++){
	$factorial=$factorial*$i;
}
echo "Factorial of $n1 : $factorial";
Output
Factorial of 5 : 120

Asking user input

We can use one sticky form to take user input and calculate the factorial of input number.
$n1=$_POST['n1'] ?? '';
echo "<form method=POST action=''>
<input type=text name=n1 value='$n1'> 
<input type=submit value=Submit>
</form>";
$factorial=1;
for ($i=1; $i<=$n1;$i++){
	$factorial=$factorial*$i;
}

echo "Factorial of $n1 : $factorial";

Factorial of a number by using recursive function

Factorial using recursive function
By using recursive function we can call the function itself from within the function.
function fact($n){
if($n<>1){	
$factorial = $n * fact($n-1);
return $factorial;
}else{
return 1;		
}
}
echo "Factorial of 6 : ".fact(6); 
Output is here
Factorial of 6 : 720
Introduction to PHP Sum of digits of a number Strong Number
Armstrong number Fibonacci Series
Basic Codes Check the string or number is Palindrome or not in PHP


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer