Calvin Moss Calvin Moss - 5 months ago 29
PHP Question

Recursion infinite loop?

So I am running into an issue that I figured out how to fix, but I am very curious as to why. So here is a block of code

<?php

function test($attempt=1){
if ($attempt == 5){
echo "Done!";
}else{
echo 'recursion!';
test($attempt++);
}

}
$test = test();


Now this code should run the first time, check, go into the else statement then run test again but this time with $attempt++ until eventually it is == to 5 and then it will echo done and complete. However this does not work and it loops forever. However it can be fixed by assigning the variable to another variable immediately after entering the function like so

<?php

function test($attempt=1){
$nextAttempt = $attempt+1;
if ($attempt == 5){
echo "Done!";
}else{
echo 'recursion!';
test($nextAttempt);
}

}
$test = test();


Any ideas as to why this is?

Answer

You want pre-increment instead of post-increment of the variable. This will increment the variable $attempt before passing it as an argument to the function instead of after.

So basically you want test(++$attempt); instead of test($attempt++);.

Sandbox with working example: http://sandbox.onlinephpfunctions.com/code/c50731815588d55bd079e701f1c5dde9e7148696

Comments