What are common pitfalls when using recursive functions in PHP?
Common pitfalls when using recursive functions in PHP include not defining a base case, which can lead to infinite recursion and cause the script to run out of memory. Another pitfall is not passing updated parameters to the recursive function, resulting in incorrect or unexpected behavior. To solve these issues, always define a base case that will stop the recursion, and make sure to pass updated parameters to the recursive function to ensure correct results.
// Example of a recursive function with a base case and updated parameters
function factorial($n, $result = 1) {
if ($n == 0) {
return $result;
} else {
return factorial($n - 1, $result * $n);
}
}
// Usage
echo factorial(5); // Output: 120