What is the concept of recursion in PHP and how can it be effectively used?
Recursion in PHP is a concept where a function calls itself within its own definition. This technique is commonly used to solve problems that can be broken down into smaller, similar sub-problems. To effectively use recursion in PHP, it is important to ensure that the base case is defined to prevent infinite loops. Example PHP code snippet demonstrating recursion:
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
// Calculate the factorial of 5
echo factorial(5); // Output: 120