Recursion & Recursive Function In PHP

Share Now

Recursion occurs when a function calls itself.

There’s nearly always an end condition of some sort — known as the base case — otherwise, the function would continue to call itself indefinitely (or at least until the computer ran out of memory).

function myRecursiveFunction() {

  // (do the required processing...)

  if ( baseCaseReached ) {

    // end the recursion
    return;

  } else {

    // continue the recursion
    myRecursiveFunction();
}

#CODE EXAMPLE

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

printNumber(1,47);

Picture of Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert