Reputation: 4601
Say, you have a condition like this;
if ($condition_1 && $condition_2)
and you have the option of writing it as
if ($condition_2 && $condition_1)
Now, if condition_1 takes 1 ms to figure it out whether it is true or false and condition_2 on the other hand takes a lot longer, say 1000ms!, which way would you write the above condition as? the slower one on the right or on the left?
I assume that when one of the conditions is found to be FALSE, PHP would not bother to check whether the other condition is TRUE. If it did, that would be the biggest surprise of the century!
Upvotes: 0
Views: 294
Reputation: 20193
C
and C++
break on first FALSE
in AND
condition. This is also the case with PHP
. So, I would suggest putting the shorter one first. This example clearly demonstrates the case:
function short(){
return false;
}
function long(){
sleep(5);// sleep for 5 secondsd
return true;
}
if ( short() && long() ){
echo "condition passed";
}else{
echo "condition failed";
}
This will almost immediately print "condition failed" without waiting for 5 seconds....
Upvotes: 2
Reputation: 13461
Conditionals are evaluated left to right. Put the shortest condition in the leftmost position. You're correct, if the leftmost condition in that if statement evals to false, the next condition isn't checked at all.
Upvotes: 9