Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Lazy Boolean Evaluation

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?

like image 402
fredley Avatar asked Nov 18 '10 15:11

fredley


2 Answers

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

like image 121
ircmaxell Avatar answered Sep 28 '22 00:09

ircmaxell


Yes, PHP does short-circuit evaluation.

like image 32
Gumbo Avatar answered Sep 27 '22 23:09

Gumbo