Recursion in PHP

Our example demonstrates recursive functions in PHP. Here’s a classic example of recursion:

<?php

// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
function fact($n) {
    if ($n == 0) {
        return 1;
    }
    return $n * fact($n - 1);
}

echo fact(7) . "\n";

// In PHP, we can define anonymous functions (closures) that can be recursive.
// We need to use the 'use' keyword to allow the function to reference itself.
$fib = function($n) use (&$fib) {
    if ($n < 2) {
        return $n;
    }
    // The function can call itself using the $fib variable
    return $fib($n - 1) + $fib($n - 2);
};

echo $fib(7) . "\n";

To run the program, save it as recursion.php and use the PHP interpreter:

$ php recursion.php
5040
13

In this example, we define two recursive functions:

  1. A traditional named function fact that calculates the factorial of a number.
  2. An anonymous function stored in the variable $fib that calculates the Fibonacci sequence.

The fact function is straightforward recursion. It calls itself with n-1 until it reaches the base case of n == 0.

For the Fibonacci function, we use an anonymous function (closure). In PHP, to make a closure recursive, we need to use the use keyword with a reference to the variable holding the function (&$fib). This allows the function to call itself.

Both functions demonstrate how recursion can be used to solve problems that have a recursive nature, such as factorial calculation and the Fibonacci sequence.