Factorial program in PHP using recursive function
Description: Write a PHP program to find the factorial of a number using a recursive function.
What is a recursive function? A recursive function is a function that calls itself, until a stopping condition is reached.
PHP program for factorial using recursion
<?php
function factorial($n) {
if ($n <= 1) {
return 1; // stopping condition
}
return $n * factorial($n - 1);
}
echo factorial(4) . "<br>";
echo factorial(5);
?>
Output:
Tutorials Class - Output Window
24
120
How it works
factorial(4)returns 4 x factorial(3), then 3 x factorial(2), then 2 x factorial(1).- When $n is 1 or less the function returns 1 and stops. Without this condition the function would call itself for ever.
- The results come back one by one: 1, then 2, then 6, then 24.
Compare it with the loop solution: factorial using a for loop.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Functions |
| Exercises & Assignments |
|---|
| Factorial program in PHP using recursive function |
| Write a PHP program to calculate area of rectangle |
| Interview Questions & Answers |
|---|
| What is PHP Function? |
| What is PHP floor() function? |
| How to count the number of parameters passed in a PHP function? |
| How can you pass a variable by reference in PHP? |