Info
Open the page on your phone

What is recursion?

Recursion is a concept in programming where a function calls itself. In PHP, as well as in many other programming languages, recursion can be used to solve tasks that can be broken down into smaller instances similar to the original problem.

For example, here's a simple PHP function that uses recursion to calculate the factorial of a number:

                        
function factorial($n) {
    if ($n <= 1) {
        return 1;
    } else {
        return $n * factorial($n - 1);
    }
}

// Example usage
$result = factorial(5);
echo $result; // Outputs 120

                        
                    

In this example, the `factorial` function calls itself with the argument `$n - 1` until `$n` becomes less than or equal to 1. When this happens, the recursion stops, and the function returns 1. Then, all the function calls are combined to obtain the final result.

Using recursion requires caution as improper usage can lead to an infinite loop and stack overflow. It's important to define a base case or exit condition for recursion to avoid these issues.