Morgan Richards
Morgan Richards

Reputation: 182

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?

Upvotes: 0

Views: 93

Answers (2)

Al Foиce    ѫ
Al Foиce ѫ

Reputation: 4315

Evaluation of logical expressions is stopped as soon as the result is known.

If $a is false, $b will not get evaluated, as it won't change the ($a && $b) result.

A consequence of that is that if the evaluation of $b requires more ressources than the evaluation of $a, starts your test condition with $a.

But be aware that:

PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code. (Source php docs)

So you should not assume $b is never evaluated if $a is false, as it may change in the future (says php docs).

Upvotes: 1

Alok Patel
Alok Patel

Reputation: 8022

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());

Upvotes: 4

Related Questions