23

let's say I have something like this:

if(1 == 0 && do_stuff()) { 
   ...
}

Obviously 1 is not 0, so there's no point to check the other condition. So does PHP ever run do_stuff() ?

1
  • 1
    If you always want "do_stuf" to be executed, you could of course have it as the first condition in the if. See my answer for the details. Commented Dec 3, 2010 at 10:45

3 Answers 3

49

No - PHP uses lazy evaluation (sometimes called short-circuit evaluation), so if the first condition in a logical AND is false, it won't attempt to evaluate any of the other conditions.

Likewise, if you were doing an OR and the first condition was true it wouldn't evaluate the second.

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

3 Comments

This is the reason why you should put expensive tests to the right
In many cases you test against variables, so the costs of the tests are insignificant. Or you have a test, that will "never" fail (like $debug in production). Then another approach is to put the the test, that will most likely fail, to the left.
This is certainly true about PHP. Anyway, it's worth noting a difference with respect to the same functionality in JavaScript. In PHP the result is always a boolean value, while in JavaScript it's the value of the last evaluated sub expression.
4

If first condition is false then php never run the second condition in && operator

Comments

1

NO, it'll not execute do_stuff() in this condition.

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.