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?

fredley
  • 32,953
  • 42
  • 145
  • 236

3 Answers3

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 &&).

nullability
  • 10,545
  • 3
  • 45
  • 63
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
  • 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 Nov 18 '10 at 15:59
  • 9
    @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`)... – ircmaxell Nov 18 '10 at 16:01
  • @Alin: Thanks! Dam google took me to the wrong docs... Fixed in the answer. Thanks! – ircmaxell Nov 18 '10 at 16:04
9

Yes, PHP does short-circuit evaluation.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
3

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

http://en.wikipedia.org/wiki/Short-circuit_evaluation#Support_in_common_programming_languages

Jere
  • 3,377
  • 1
  • 21
  • 28