ayaya Posted January 1, 2013 Share Posted January 1, 2013 <? function f($a) { if($a<2) { echo "before:".$a."</br>"; f($a+1); echo "after:".$a."</br>"; } } f(0); ?> Why the result is: before:0 before:1 after:1 after:0 Can anyone help? Link to comment https://forums.phpfreaks.com/topic/272593-php-recursion-question/ Share on other sites More sharing options...
trq Posted January 1, 2013 Share Posted January 1, 2013 Makes perfect sense to me. What exactly were you expecting? Link to comment https://forums.phpfreaks.com/topic/272593-php-recursion-question/#findComment-1402644 Share on other sites More sharing options...
Jessica Posted January 1, 2013 Share Posted January 1, 2013 Your code basically does this: call f(0); echo before: 0 call f(1); echo before: 1; call f(2); exit f(2) echo after: 1; exit f(1); echo after: 0; Link to comment https://forums.phpfreaks.com/topic/272593-php-recursion-question/#findComment-1402645 Share on other sites More sharing options...
ayaya Posted January 1, 2013 Author Share Posted January 1, 2013 exit f(2) echo after: 1; exit f(1); echo after: 0; Thank you for your help. But if exit f(2) and f(1), How comes the result after "afer"? I still don't understand it. Sorry I'm very stupid... Link to comment https://forums.phpfreaks.com/topic/272593-php-recursion-question/#findComment-1402649 Share on other sites More sharing options...
DavidAM Posted January 1, 2013 Share Posted January 1, 2013 Each invocation of the function is a separate occurance and gets its own local variables. The recursive call is NOT modifying $a. For that matter, you are not modifying it locally. If you want the recursive call to affect the local variable, you would have to pass by reference or return it: function f($a) { if($a<2) { echo "before:".$a."</br>"; $a = f($a+1); echo "after:".$a."</br>"; } return $a; } f(0); Link to comment https://forums.phpfreaks.com/topic/272593-php-recursion-question/#findComment-1402659 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.