27

I have a conditional statement thus:

if($boolean && expensiveOperation()){ ...}

Does PHP have lazy boolean evaluation, i.e. will it check $boolean and if it is false not bother performing the expensive operation? If so, what order should I put my variables?

5
  • I would generally refrain from putting 2 operations in the same line of code if they are not inherently related. It makes readability difficult and you don't gain computing time or resources. Commented Nov 18, 2010 at 16:02
  • 1
    Apols for my incorrect answer (now deleted). I thought I remembered trying this out and finding it didn't work, but I'm obviously mistaken. Commented Nov 18, 2010 at 16:05
  • @Nathan At least you got a Peer Pressure badge :) Commented Nov 18, 2010 at 16:07
  • @Alin Purcaru Is that a good thing? :) Commented Nov 18, 2010 at 16:08
  • @Nathan It shows you're responsible... or afraid of loosing reputation points. Commented Nov 18, 2010 at 16:10

3 Answers 3

32

Yes it does. It's called short-circuit evaluation. See the comments on the documentation page...

As for the order, it performs the checks based on Operator Precedence and then left to right. So:

A || B || C

Will evaluate A first, and then B only if A is false, and C only if both A and B are false...

But

A AND B || C

Will always evaluate B || C, since || has a higher precedence than AND (not true for &&).

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

3 Comments

if you want the non-shor-circuit evaluation you can use a single & which would be a boolean union function. It would compute both values and then try to perform an AND between them.
@Mikhail: Yes. But you must be careful as the singe & is actually a bit-wise operator. So true & 2 would be false (since true is 00000001, and 2 is 00000010, so the AND would be 00000000)...
@Alin: Thanks! Dam google took me to the wrong docs... Fixed in the answer. Thanks!
9

Yes, PHP does short-circuit evaluation.

Comments

3

PHP does have short circuit evaluation. Your example would be the proper use of it:

https://en.wikipedia.org/wiki/Short-circuit_evaluation#Support_in_common_programming_and_scripting_languages

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.