What are common pitfalls when using recursion in PHP functions, as seen in the provided code?
One common pitfall when using recursion in PHP functions is not having a base case to terminate the recursive calls, leading to infinite recursion and potential stack overflow. To solve this issue, always ensure there is a base case that checks for a condition to stop the recursion.
// Incorrect recursive function without a base case
function factorial($n) {
return $n * factorial($n - 1);
}
// Corrected recursive function with a base case
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
Related questions
-
PHP API optimization
-
database integration session management PHP applications
-
syntax errors undefined variables SQL injection