You are here: Home / Topics / Program for Factorial in PHP with PHP "for loop"

Program for Factorial in PHP with PHP "for loop"

Filed under: PHP on 2022-10-30 19:47:51

In this post, we are going to see how to write a PHP function to calculate the factorial of a given number in PHP using for loop. The factorial of a number is the product of all integers between 1 and itself.

Code

<?php  
function fact($n){    
$f = 1;    
for ($i = 1; $i <= $n; $i++){      
$f = $f * $i;    
}    
return $f;  
}      
$n = 4;  
$f = fact($n);  
echo "Factorial of $n is $f";
?>

Output of this program will be 

Factorial of 4 is 24

About Author:
T
Team MCQ Buddy     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.