Jay Bhatt
Jay Bhatt

Reputation: 5651

PHP recursive function

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.

Upvotes: 0

Views: 1149

Answers (2)

Gordon
Gordon

Reputation: 316969

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)

Upvotes: 2

dev-null-dweller
dev-null-dweller

Reputation: 29462

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.

Upvotes: 2

Related Questions