What is recursion in PHP and how is it used?
Recursion in PHP is a programming technique where a function calls itself in order to solve a problem. This can be useful for tasks that can be broken down into smaller, similar subtasks. To use recursion in PHP, you define a function that calls itself within its own definition until a certain condition is met to stop the recursion. Example PHP code snippet demonstrating recursion:
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
// Test the factorial function
echo factorial(5); // Outputs 120