Lesson 30 of 50 – PHP Recursive Functions
60%

PHP Recursive Functions

Recursion is a programming technique in which a function calls itself to solve a problem. A recursive function needs a base case to stop the repeated calls.

1. What Is Recursion?

A recursive function calls itself from inside its own definition. Each call works toward a stopping condition.

<?php
function countDown($number) {
    if ($number <= 0) {
        return;
    }

    echo $number . "<br>";

    countDown($number - 1);
}

countDown(5);
?>
Output:
5
4
3
2
1

The function prints the current number and then calls itself with a smaller number. When the number reaches zero, the function returns without making another call.

2. Understanding the Base Case

The base case is the condition that stops recursion. Without a reachable base case, a recursive function may continue calling itself until PHP encounters a resource or execution limit.

<?php
function printNumber($number) {
    if ($number == 1) {
        echo "Finished";
        return;
    }

    echo $number . "<br>";

    printNumber($number - 1);
}

printNumber(4);
?>
Output:
4
3
2

When $number becomes 1, the base case is reached. The function displays "Finished" and returns.

Notice that the base case is checked before the recursive call.

3. Calculating Factorial Using Recursion

The factorial of a positive integer is the product of all positive integers from 1 to that number. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

<?php
function factorial($number) {
    if ($number <= 1) {
        return 1;
    }

    return $number * factorial($number - 1);
}

echo factorial(5);
?>
Output:
120

How it works:

factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120

This example assumes a non-negative integer input. For a production application, validate the input and consider the limits of factorial calculations.

4. Finding the Sum of Numbers

Recursion can calculate the sum of integers from 1 to a given positive integer.

<?php
function sumNumbers($number) {
    if ($number <= 0) {
        return 0;
    }

    return $number + sumNumbers($number - 1);
}

echo sumNumbers(5);
?>
Output:
15

The calculation is:

5 + 4 + 3 + 2 + 1 = 15

When the number reaches zero, the function returns zero and the previous calls add their values together.

5. Fibonacci Series Using Recursion

In the Fibonacci sequence, each number after the first two is the sum of the previous two numbers. This recursive example calculates a Fibonacci number.

<?php
function fibonacci($number) {
    if ($number <= 1) {
        return $number;
    }

    return fibonacci($number - 1)
         + fibonacci($number - 2);
}

echo fibonacci(6);
?>
Output:
8

This function uses zero-based positions:

Position:  0  1  2  3  4  5  6
Value:     0  1  1  2  3  5  8

This simple recursive implementation repeats many calculations. It is useful for learning recursion, but an iterative or memoized approach is more efficient for larger positions.

6. Displaying an Array Recursively

Recursion can process array elements one at a time. The function stops when the index reaches the number of elements in the array.

<?php
function displayArray($items, $index = 0) {
    if ($index >= count($items)) {
        return;
    }

    echo $items[$index] . "<br>";

    displayArray($items, $index + 1);
}

$fruits = ["Apple", "Mango", "Banana", "Orange"];

displayArray($fruits);
?>
Output:
Apple
Mango
Banana
Orange

Each call displays one array element and increases the index. The recursion stops when no elements remain.

For ordinary array traversal, a foreach loop is usually simpler.

7. Reversing a String Using Recursion

A string can be reversed recursively by taking its last character and adding the reverse of the remaining string.

<?php
function reverseString($text) {
    if (strlen($text) <= 1) {
        return $text;
    }

    return substr($text, -1)
         . reverseString(substr($text, 0, -1));
}

echo reverseString("PHP");
?>
Output:
PHP

Try another example:

<?php
echo reverseString("HELLO");
?>
Output:
OLLEH

This example uses byte-oriented string functions. Multibyte text, such as many Hindi or other Unicode strings, needs a Unicode-aware approach.

8. Recursion vs. Loops

Both recursion and loops can repeat operations. Recursion uses function calls, while loops repeat a block of statements.

Using Recursion:
<?php
function printOneToFive($number) {
    if ($number > 5) {
        return;
    }

    echo $number . "<br>";

    printOneToFive($number + 1);
}

printOneToFive(1);
?>
Using a Loop:
<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . "<br>";
}
?>
Output from Both Examples:
1
2
3
4
5

A loop is generally preferable for simple repetition. Recursion is especially useful when a problem naturally breaks into smaller versions of itself, such as traversing nested structures.

9. Practical Example: Calculate Power Recursively

This example calculates a number raised to a non-negative integer power.

<?php
function power($base, $exponent) {
    if ($exponent == 0) {
        return 1;
    }

    return $base * power($base, $exponent - 1);
}

echo power(2, 4);
?>
Output:
16

The calculation is:

2 * 2 * 2 * 2 = 16

The base case is when the exponent reaches zero. Any non-zero number raised to the power zero returns 1.

This example assumes a non-negative integer exponent.

Practice Assignments
  1. Create a recursive function that prints numbers from 1 to 10.
  2. Create a recursive function that counts down from 10 to 1.
  3. Calculate the factorial of 6 using recursion.
  4. Calculate the sum of numbers from 1 to 10 using recursion.
  5. Calculate the Fibonacci number at position 7.
  6. Display all elements of an array using recursion.
  7. Reverse a simple English word using recursion.
  8. Calculate 3 raised to the power 4 using recursion.
  9. Write a recursive function that finds the greatest common divisor (GCD) of two positive integers.

🧠 Quick Quiz

1. What is recursion?




2. What is the purpose of a base case?




3. What is factorial of 5?