Is recursion or iteration a better approach for solving the given problem in PHP?
The given problem involves calculating the factorial of a number. Recursion can be a better approach for solving this problem as it simplifies the logic and makes the code more concise. By using recursion, we can repeatedly call the function with a smaller input until we reach the base case.
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
// Example usage
echo factorial(5); // Output: 120