0

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?

5
  • Iirc, no, the evaluation will stop (and fail) at $a. Commented Oct 18, 2016 at 9:25
  • php evaluates quite lazy. since $a is false, the expression will be false regardless of $b, so there is no reason to evaluate $b. (extensively covered in the manual and tutorials, AFAICR). also, you could've checked yourself by using functions that echo something and return a boolean. Commented Oct 18, 2016 at 9:26
  • No it will not be evaluated because it short circuits. Commented Oct 18, 2016 at 9:26
  • Also with opcache there are cases when the entire if isn't executed. Commented Oct 18, 2016 at 9:27
  • In theory, you shouldn't assume an order of operations since future versions may change it and evaluate $b and then $a. In practice everyone already assumes that $b is not evaluated so it's doubtful that this change will ever happen, so as it stands now, $a is evaluated and if it's false then the whole if fails (without evaluating $b) Commented Oct 18, 2016 at 9:50

2 Answers 2

4

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());
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks for the clariffication useful to know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.