Search code examples
phpif-statementoperator-precedence

PHP if execution


In PHP if you have the following code does $b get evaluated since $a will cause the if statement to return false?

$a = false;
$b = true;

if ($a && $b) {
  // more code here
}

also if $b does get evaluated are there ever circumstances where a portion of an if statement may not be evaluated as the processor already knows that the value to be false?


Solution

  • Evaluation of && is stopped as soon as it hits the false condition.

    These (&&) are short-circuit operators, so they don't go to check second condition if the first one true (in case of OR) or false(in case of AND).

    Reference: http://php.net/manual/en/language.operators.logical.php


    From documentation:

    <?php
    
    // --------------------
    // 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());