Reputation: 5651
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
Reputation: 316969
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;
$count
is 11, it will keep calling getX()
with $count
(1+2)if
is false
it will start processing the remaining code, e.g. it will return $count
(3)$countTemp
(4+5)$count
is returned again until it's back at the original callee. (5 back to 4)Upvotes: 2
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