If you have two consecutive conditions in PHP, do they both get evaluated, or is the if-case evaluation cancelled if the first condition already failed (so the result of the second condition wouldn't matter)?
if (condition1 && condition2) { }
If you have two consecutive conditions in PHP, do they both get evaluated, or is the if-case evaluation cancelled if the first condition already failed (so the result of the second condition wouldn't matter)?
if (condition1 && condition2) { }
PHP uses Short Circuit Evaluation, so the second condition would not even be evaluated if the first one is false.
Since you are using &&
, if the left condition fail the right ones wont be evaluated
if (statement1 && statement2)
{
//If the left part is false, the right part is not even checked
}
if (statement1 || statement2)
{
//if the left part is false, the right part is checked
}
If the result of the first condition makes evaluating the second condition unnecessary, PHP won't evaluate it (the second condition). This is called Short-circuit evaluation, a term that is also meantioned in PHP's documentation on logical operators.
Here is a small example to prove it:
<?php
function foo() {
echo 'Bar';
return true;
}
if (false && foo()) { }
Because PHP uses Short-circuit evaluation, foo()
will not be executed, and therefore Bar
will not be printed on the screen.
Because 'Test' will never be echo
ed, you can conclude that if the first condition returns false
, the second condition is never evaluated.
The same works for ||
(OR) operators, but the other way around:
<?php
function foo() {
echo 'Bar';
return true;
}
if (true || foo()) { }
Since the first condition is already true
, there is no need to evaluate the second one. Again, foo()
is not executed, so you'll get an empty screen.
Its an AND. And PHP is lazy as hell. If the first functions returns false, it will not touch the other functions. Its the same with OR. If you use it, PHP is lazy and only evaluates as long as necessary.
if(condition1() || condition2())
If condition1()
returns true
, condition2 will be untouched. Its nice to know for performance, always evaluate the fast functions first in that case.^^