0

I am new to the concept of recursion. I have created the following example to try and understand recursion. But I am having difficulties and would appreciate your help.

function getX($count){
    $count++;
    if($count <= 10){
        $countTemp = getX($count);
        echo $countTemp; //Shouldn't this skipped?
    }
    return $count;
}

getX(0);

My confusion is that the above function prints 11, 10, 9, 8....1 but shouldn't the code echo $countTemp; be ignored as the statement above it causes recursion? I might be comparing recursion with looping here.

tereško
  • 58,060
  • 25
  • 98
  • 150
Jay Bhatt
  • 5,601
  • 5
  • 40
  • 62
  • I guess it's concrete enough to not close that as dupe of http://stackoverflow.com/questions/2648968/what-is-a-recursive-function-in-php – Gordon Aug 03 '13 at 11:58
  • Have read this once on SO: To understand recursion, you must first understand recursion. :) – hek2mgl Aug 03 '13 at 12:03
  • 1
    *but shouldn't the code echo $countTemp; be ignored as the statement above it causes recursion?* It is not skipped. Recursion here have depth limit, so the control is passed back to place after function call. – Cthulhu Aug 03 '13 at 12:04

2 Answers2

2

It is not and should not be ignored, just deferred execution - that's why you are getting numbers in reversed order. When $count reaches 11, code in if condition is skipped and value of $count is returned to 10th iteration (inside if) and echoed as $countTemp. In this iteration $count was 10 and this is returned to 9th iteration and again echoed as $countTemp.

dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
2

The order of execution is this:

if 1 <= 10 true call getX(1)
    if 2 <= 10 true call getX(2)
        if n <= 10 call getX(n)
            if 11 <= 10 false
            // now go all the way back to the getX(0)
            return and echo 11;
        return and echo n;
    return and echo 2;
return and echo 1;

Visualized on your code:

recursion explained

Explained in words:

  • Until $count is 11, it will keep calling getX() with $count (1+2)
  • Once your if is false it will start processing the remaining code, e.g. it will return $count (3)
  • This then gets assigned and echo'ed as $countTemp (4+5)
  • Then $count is returned again until it's back at the original callee. (5 back to 4)
Gordon
  • 312,688
  • 75
  • 539
  • 559