Recursion in PHP with example
Recursion in PHP
In PHP, recursion is a process in which a function calls itself. It is mainly used in those situations where a task can be broken down into smaller, similar tasks. Every recursive function must have two main parts to prevent infinite loops:
- Base Case: A condition that, when met, stops the recursion and returns a value. This is the exit condition.
- Recursive Case: The part of the function that performs the action and calls itself again with modified arguments, moving closer to the base case with each call.
Example: A classic example of recursion is calculating the factorial of a number (n!), which is the product of all positive integers less than or equal to n. The mathematical definition of a factorial is inherently recursive:
- 0! = 1 (Base Case)
- n! = nx(n-1)! (Recursive Case)
<?php
function factorial(int $n): int {
// Base Case: Stop the recursion when n is 0 or 1
if ($n <= 1) {
return 1;
} else {
// Recursive Case: Call the function again with a smaller number
return $n * factorial($n - 1);
}
}
$number = 5;
echo "The factorial of $number is: " . factorial($number);
?>
Output:
The factorial of 5 is: 120