Home »
PHP »
PHP programs
Find factorial of a number in PHP
In this article, we are going to learn how to find factorial of a given number using PHP program?
Submitted by IncludeHelp, on January 05, 2018
Given a number and we have to find its factorial.
Formula to find factorial: 5! (Factorial of 5) = 5x4x3x2x1 = 120
Example:
Input: 5
Output: 120
Program to find factorial of a number in PHP
<?php
//program to find factorial of a number
//here, we are designing a function that
//will take number as argument and return
//factorial of that number
//function: getFactorial
function getFactorial($num){
//declare a variable and assign with 1
$factorial = 1;
for($loop = 1; $loop <= $num; $loop++)
$factorial = $factorial * $loop;
return $factorial;
}
//Main code to test above function
$number = 1;
print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
$number = 2;
print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
$number = 3;
print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
$number = 4;
print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
$number = 5;
print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n");
?>
Output
Factorial of 1 is = 1
Factorial of 2 is = 2
Factorial of 3 is = 6
Factorial of 4 is = 24
Factorial of 5 is = 120
PHP Basic Programs »
TOP Interview Coding Problems/Challenges