3

I have the following PHP function

function newUser($username, $password) {
     $checkUsernameAvailablity = check($username);
     if (!$checkUsernameAvailablity)
         {
           return -1;
         } 

         $checkPasswordComplexity = checkpass($password);
         if (!$checkPasswordComplexity)
         {
           return -2
         }

}

I would like to know if the username is taken and the password is not complex enough, will PHP stop the function after it returns -1 or will it continue and return -2 also.

Thanks in advance, RayQuang

5
  • The question is will PHP stop the function after it finished the first return statement or will it continue? Commented Nov 17, 2010 at 7:35
  • @RayQuang - If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file. , more - php.net/manual/en/function.return.php Commented Nov 17, 2010 at 7:37
  • The code also contains an error... if (!$checkpass) will never evaluate as true since it's an undefined variable ... you should evaluate $checkPasswordComplexity Commented Nov 17, 2010 at 7:39
  • Oh sorry about the mistakes, This is not the actual code I just made it up to illustrate the point. Commented Nov 17, 2010 at 7:41
  • @RayQuang: just curiuos, why did not you try before ask? Commented Nov 17, 2010 at 7:47

3 Answers 3

6

When execution reaches a return statement, the function will stop and return that value without processing any more of the function.

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

Comments

3

return statement returns the value and terminates the execution of the function. If the return is hit, no further code is executed in that body.

By the way, not all code paths have return values.

2 Comments

Be careful there: Unless the script exists, all code paths have return values, just that those values can be null. A blank return returns NULL and there is an implicit return at the end of a function that doesn't otherwise have a return call.
NULL is arguable a value. It means 'no value'. It's just that the result is far more obvious when you actually return something. You then know what to expect. In PHP it may not be a big deal, but I'm used to having implicit return values. In some other, "orthodox" languages, that just wouldn't compile.
2

the design of your function is wrong.

I would return different values when the function ends accordingly.

For multiple returns I would use switch or a properly designed IF statements.

Or better return an associative array.

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.