I’m just doing some recursion exercises in PHP and I’m a bit baffled by the output of the following:
function calc($numTimes, $i, $total) {
if (!$i && !$total) {$i = 1; $total = 1;}
if ($i <= $numTimes) {
$total = $total*2;
$i++;
calc($numTimes, $i, $total);
}
echo $total.'+'.$i.'<br />';
}
calc(5);
Before running it I would’ve assumed the output to be 32+6. However, this is what I get:
32+6
32+6
16+5
8+4
4+3
2+2
I don’t get it. The output is not only 5 lines longer than I would’ve expected it to be, but instead of incrementing the total, it’s removing from it? Also, if I add a break; after the echo, it only returns 32+6, which somehow seems relevant. However, when I change the code so that it uses return $total; instead of echo:
function calc($numTimes, $i, $total) {
if (!$i && !$total) {$i = 1; $total = 1;}
if ($i <= $numTimes) {
$total = $total*2;
$i++;
calc($numTimes, $i, $total);
}
return $total.'+'.$i.'<br />';
}
$r = calc(5);
echo $r;
This is what gets printed out:
2+2
I’m a bit confused and hoping someone can help me understand what’s going on here.
you are not doing anything with the recursive call.
the line:
might calculcate a value, but does nothing with it. notice that the returned value is never saved. you would have to fetch it:
and then keep going with $res
i think what you meant is: