Search code examples
phpoptimizationconditional-statementsshort-circuiting

PHP if OR is the second part checked on true?


I know this must be a simple question, but I know that in PHP in a statement like this

if ($a && $b) { do something }

if $a is false PHP doesn't even check $b

Well is the same thing true about OR so

if ($a || $b) { do something }

If $a is true, does it still check $b

I know this is elementary stuff, but I can't find the answer anywhere... Thanks


Solution

  • See Example 1 on the Logical Operators page in the manual.

    // --------------------
    // foo() will never get called as those operators are short-circuit
    
    $a = (false && foo());
    $b = (true  || foo());
    $c = (false and foo());
    $d = (true  or  foo());