A recursive function is a function that calls itself. This technique is used to solve problems that can be broken down into smaller, similar sub-problems, such as traversing file directories or calculating mathematical sequences.
Every successful recursive function must have two main components to avoid infinite loops:
This function echoes a number and then calls itself with a smaller number until it reaches zero.
<?php
function countDown($number) {
if ($number <= 0) { // Base Case
echo "Blast off!";
return;
}
echo $number . "... ";
countDown($number - 1); // Recursive Case
}
countDown(5); // Outputs: 5... 4... 3... 2... 1... Blast off!
?>
Factorial calculation is the classic use case for recursion. 5! is $5 \times 4 \times 3 \times 2 \times 1$.
<?php
function factorial($n) {
if ($n <= 1) { // Base Case
return 1;
}
return $n * factorial($n - 1); // Recursive Case
}
echo factorial(5); // Outputs: 120
?>
for or while) because each function call adds a new layer to the system stack.