Recursion & Recursive Function In PHP

Quick Summary

  • A recursive function calls itself until a base case ends it; without that end condition PHP runs out of memory and stops.
  • The printNumber() example prints 1 to 47 by printing the counter, adding one and calling itself until the counter passes the end.
  • Recursion suits nested data such as menus, category trees and folders, though very deep recursion can hit PHP's memory limit.

Recursion occurs when a function calls itself, which makes it a recursive function. There is nearly always an end condition of some sort, known as the base case. Without it, the function would keep calling itself until PHP runs out of memory and the script stops with a fatal error.

The basic pattern

This outline shows the structure of a recursive function. It isn’t runnable code: baseCaseReached stands for whatever condition means the work is done, and the function’s own closing brace is missing, so add it if you use this as a template.

PHP
function myRecursiveFunction() {

  // (do the required processing...)

  if ( baseCaseReached ) {

    // end the recursion
    return;

  } else {

    // continue the recursion
    myRecursiveFunction();
}

Each call does its share of the work, then either stops (the base case) or calls itself again with the problem one step closer to the end.

Example: print the numbers from 1 to 47

PHP
function printNumber($counter, $end){
    if($counter>$end){
        return;
    }
    echo $counter."\n";
    $counter++;
    printNumber($counter, $end);
}

printNumber(1,47);
  • printNumber(1,47) starts the recursion. $counter is the current number and $end the last one to print.
  • The base case is $counter>$end: once the counter passes the end, the function returns without calling itself, and the recursion stops.
  • Otherwise it prints the counter followed by a line break ("\n"), adds one to the counter and calls printNumber() again with the new value.
  • Run from the command line, the output is 1 to 47, one number per line. In a browser, "\n" shows as a space; use <br> there instead.

A simple loop could print these numbers too, and printing the Fibonacci series in PHP works with the same pattern. Recursion is most useful for nested data, such as menus with sub-items, category trees or folders inside folders. Keep in mind that every call adds to the call stack, so very deep recursion can hit PHP’s memory limit.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More