Factorial of a Number using PHP

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
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



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-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer