Reputation: 731
I have a performance related question regarding how PHP evaluates the OR operator in a conditional.
I have a conditional that calls 2 functions, both returning booleans:
The first is a simple, fast function - simpleFunction()
The second is a more intensive function that queries the DB - intensiveFunction()
I could write the conditional like this, so that if the first, simple function returned TRUE, the second more intense function would not be executed:
if ( simpleFunction() ) {
// Do Stuff
} elseif ( intensiveFunction() ) {
// Do the same stuff (redundant code)
}
My question is, when using and OR operator in a PHP conditional, if the first condition (on the left of the operator) is TRUE, will the second function (on the right side of the operator) be executed?
if ( simpleFunction() || intensiveFunction() ) {
//Do Stuff
}
This conditional will be running inside a loop, so I would like to avoid running intensiveFunction() on every iteration.
Upvotes: 0
Views: 107
Reputation: 229
Additionally compare this script testing the various logical operators:
<pre>
<?php
function test($bool) {
echo "I was executed\n";
return $bool;
}
echo "<b>||-Operator</b>\n";
if (test(true) || test(true)) {
;
}
echo "<b>|-Operator</b>\n";
if (test(true) | test(true)) {
;
}
echo "<b>or-Operator</b>\n";
if (test(true) or test(true)) {
;
}
echo "<b>&&-Operator</b>\n";
if (test(false) && test(true)) {
;
}
echo "<b>&-Operator</b>\n";
if (test(false) & test(true)) {
;
}
echo "<b>and-Operator</b>\n";
if (test(false) and test(true)) {
;
}
?>
</pre>
Output:
||-Operator
I was executed
|-Operator
I was executed
I was executed
or-Operator
I was executed
&&-Operator
I was executed
&-Operator
I was executed
I was executed
and-Operator
I was executed
Note that | and & always execute the second part even when the output can't be true (&-Operator) anymore or can't become false (|-Operator) anymore.
Upvotes: 2
Reputation: 731
As Neal pointed out, I should have just tested this:
$hasRun = 'Intesive Function Has NOT Run';
function simpleFunction() {
return TRUE;
}
function intensiveFunction() {
$hasRun = 'Intesive Function Has Run';
return TRUE;
}
if ( simpleFunction() || intensiveFunction() ) {
echo $hasRun;
}
//Result: Intesive Function Has NOT Run function
So yes, once the first condition returns TRUE the conditional exits and the second condition is not evaluated.
Upvotes: 0
Reputation: 146310
I believe that once a truthy is found in an or operation, then the statement ends and returns true
,
Whereas in an and operation, it runs until it finds a falsey.
Upvotes: 6