2

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?

1
  • Also, you realize that setting $test = test() does nothing, since test() doesn't return a value, right? Commented Jun 6, 2016 at 22:00

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Took me a few minutes to see it out myself, it isn't something too obvious ;-) Happy to have helped!
You could easily catch such issues if you have a proper debugging setup (eg. xdebug) to step through your code.
I agree with @georaldc ...with xdebug you could watch the variable values change with each loop and see very clearly what is happening in your code. It is an extremely valuable tool that I would advise you figure out how to use ASAP. There can be challenges setting it up, but well worth it in allowing you to debug your code much more easily.
1

The operator ++ executes after the evaluation of the sentence, so you are executing the call to the function with the same value ever.

test($attempt++);

is the same than:

test($attempt);
$attempt = $attempt  + 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.