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.

3
  • I guess it's concrete enough to not close that as dupe of stackoverflow.com/questions/2648968/… Commented Aug 3, 2013 at 11:58
  • Have read this once on SO: To understand recursion, you must first understand recursion. :) Commented Aug 3, 2013 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. Commented Aug 3, 2013 at 12:04

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.