PHP › Functions & Scope

How does recursion work in PHP functions, and what are the practical considerations, such as stack depth limits, when writing a recursive function?

Advanced

Answer

A recursive function is a function that calls itself, typically to solve a problem that can naturally be broken down into smaller instances of the same problem, such as traversing a nested directory structure or calculating a factorial, and while recursion can produce elegant, readable solutions, PHP has a practical limit on how deeply functions can call themselves before running out of available memory for the call stack, meaning very deep recursion on large datasets should generally be converted to an iterative loop based approach instead.
function factorial($n) {
    if ($n <= 1) return 1;
    return $n * factorial($n - 1);
}
echo factorial(5);
Real-world example A file system scanning tool uses a recursive function to traverse deeply nested folder structures, but the team adds a maximum depth safeguard after discovering that an unusually deep folder structure could otherwise risk exhausting the available call stack.

Common follow-ups: What is a base case in a recursive function and why is it essential?;How do you convert a recursive function into an equivalent iterative version?