PHP Recursive Functions

A recursive function is a function that calls itself until a base condition is met. Recursion is useful for solving problems that can be broken down into smaller subproblems, like calculating factorials or traversing directories.

🔹 How Recursion Works

Every recursive function must have:

  • 🔸 A base case that stops recursion.
  • 🔸 A recursive call that moves towards the base case.

📝 Example 1: Factorial Using Recursion

Factorial of a number n (written as n!) is calculated as:

n! = n × (n - 1) × (n - 2) × ... × 1

For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

<?php
function factorial($n) {
    if ($n == 1) {
        return 1; // Base case
    }
    return $n * factorial($n - 1); // Recursive call
}

echo "Factorial of 5 is: " . factorial(5);
?>

Try It Now

Explanation:

  • If $n == 1, the function stops (base case).
  • Otherwise, it multiplies $n by factorial($n - 1), calling itself recursively.

📝 Example 2: Sum of Natural Numbers

Recursion can also be used to find the sum of the first n natural numbers.

<?php
function sumNumbers($n) {
    if ($n == 1) {
        return 1; // Base case
    }
    return $n + sumNumbers($n - 1); // Recursive call
}

echo "Sum of first 5 natural numbers: " . sumNumbers(5);
?>

Try It Now

Explanation:

  • If $n == 1, the function stops (base case).
  • Otherwise, it adds $n to sumNumbers($n - 1), calling itself recursively.

📝 Example 3: Traversing a Directory Recursively

Recursion is useful for navigating directories and subdirectories.

<?php
function listFiles($dir) {
    $files = scandir($dir);
    
    foreach ($files as $file) {
        if ($file != "." && $file != "..") {
            $filePath = "$dir/$file";
            if (is_dir($filePath)) {
                listFiles($filePath); // Recursive call for subdirectories
            } else {
                echo "File: $filePath <br>";
            }
        }
    }
}

// Call function with a directory path
listFiles("path/to/directory");
?>

Try It Now

Explanation:

  • Uses scandir() to list files in a directory.
  • For subdirectories, calls itself recursively to list files inside them.

🔹 Key Points to Remember

  • Recursion is when a function calls itself.
  • Every recursive function must have a base case to prevent infinite loops.
  • Recursion is useful for mathematical problems, searching, and file system traversal.

📝 Practice Time!

Modify these examples and experiment with PHP recursive functions for a deeper understanding! 🚀