Friday, October 24, 2025
HomeLanguagesPHP | Factorial of a number

PHP | Factorial of a number

We already know how to get the factorial of a number in other languages. Let’s see how this is done in PHP using both recursive and non-recursive ways. Examples:

Input : 5
Output : 120

Input : 10
Output : 3628800

Method 1: Iterative way In this method, we simply used the for loop to iterate over the sequence of numbers to get the factorial. 

PHP




<?php
// PHP code to get the factorial of a number
// function to get factorial in iterative way
function Factorial($number){
    $factorial = 1;
    for ($i = 1; $i <= $number; $i++){
    $factorial = $factorial * $i;
    }
    return $factorial;
}
 
// Driver Code
$number = 10;
$fact = Factorial($number);
echo "Factorial = $fact";
?>


Output:

3628800

Time Complexity: O(N) where N is the number of which factorial is being calculated

Auxiliary Space: O(1)

Method 2: Use of recursion In this method we are calling the same method to get the sequence of the factorial. 

PHP




<?php
// PHP code to get the factorial of a number
// function to get factorial in iterative way
function Factorial($number){
    if($number <= 1){
        return 1;
    }
    else{
        return $number * Factorial($number - 1);
    }
}
 
// Driver Code
$number = 10;
$fact = Factorial($number);
echo "Factorial = $fact";
?>


Output:

3628800

Time Complexity: O(N) where N is the number of which factorial is being calculated

Auxiliary Space: O(N)

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS