Simulating Recursion in PHP Using Stacks, Loops, and Goto
This article explains how to replace recursive functions in PHP with stack‑based iteration, loop‑driven depth‑first tree traversal, and even a goto‑based approach, providing complete code examples and discussing the trade‑offs of each method.
Recursion is often used for tasks such as factorials, Fibonacci numbers, and tree traversal, but deep recursion can cause stack overflow and performance issues, so iterative alternatives are sometimes preferred.
This article demonstrates three ways to simulate recursion in PHP without calling functions.
1. Using a stack to calculate factorials
$n = 5; // number to calculate factorial for
$stack = [$n]; // initialize stack with the starting number
$result = 1;
while (!empty($stack)) {
$current = array_pop($stack);
$result *= $current;
if ($current > 1) {
$stack[] = $current - 1; // push the next value onto the stack
}
}
echo "Factorial of $n: $result\n";Explanation:
Simulates function calls by storing parameters on a stack.
Iteratively pops values and multiplies them.
Continues pushing decremented values until 1 is reached.
2. Using a stack for depth‑first tree traversal (DFS)
$tree = [
'value' => 1,
'left' => [
'value' => 2,
'left' => null,
'right' => null
],
'right' => [
'value' => 3,
'left' => null,
'right' => null
]
];
$stack = [$tree];
$values = [];
while (!empty($stack)) {
$node = array_pop($stack);
if ($node === null) {
continue;
}
$values[] = $node['value'];
// push right then left child so left is processed first
if (isset($node['right'])) $stack[] = $node['right'];
if (isset($node['left'])) $stack[] = $node['left'];
}
echo "Depth-First Traversal: " . implode(', ', $values) . "\n";Explanation:
Pushes the right child first, then the left child, ensuring left‑most nodes are visited first.
Pops a node, processes its value, and repeats until the stack is empty.
Provides a non‑recursive implementation of DFS.
3. Using goto to simulate recursion (not recommended)
$n = 5; // number for factorial
$result = 1;
start:
if ($n <= 1) {
echo "Factorial: $result\n";
return;
}
$result *= $n;
$n--;
goto start; // jump back to the start labelExplanation:
The goto repeatedly jumps to the label, mimicking recursive calls.
Each iteration multiplies the current $n and decrements it.
When $n reaches 1, the loop ends and the result is printed.
While goto can emulate recursion, it leads to “spaghetti code” that is hard to read and maintain; modern PHP standards favor loops, functions, generators, or closures for clearer, more maintainable solutions.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.