PHP Does IF stop checking AND operator if first condition not met.?

  • Thread starter Thread starter Drale
  • Start date Start date
D

Drale

Guest
When two conditions must both be met, if the first one is not met does it just skip and not bother checking the other condition?

example:
if(5 = 4 && $x != $y){
}

Does it even check to see if $x != $y? Because 5 doesn't equal 4, so whether or not $x != $y is correct the IF statement will fail anyways.

I'm curious because if it does skip the second condition, it would be good practice to put the more complicated calculations/functions as the second condition.
I meant 5 == 4 not 5 = 4
 
DzSoundNirvana is wrong. The other answers are correct, in an AND statement, if the first condition is wrong, the IF condition will stop. You can test this yourself in PHP:

if (5 == 4 && noSuchFunction() == false) ;

That script will run just fine, no errors. That tells you since 5 != 4, the IF statement stopped completely before reaching the second condition. But this:

if (5 == 5 && noSuchFunction() == false) ;

will make PHP bomb out with an error stating that noSuchFunction is not defined.
 
Most of the common computer languages use short circuit evaluation. If the value of the logical operator is fully determined by the first operand, the second operand is not evaluated.

For the AND operator (&&), if the first operand is false, the second is not evaluated.

For the OR operator (||), if the first operand is true, the second is not evaluated.

The point is that once the end result is known, there is no need to waste time on other calculation.
 
It will continue to the second evaluation even if the 1st is false. because of &&. Use || if you want it to stop for either one.

false,Null is the outcome

the whole evaluation will evaluate to false. because of 5==4
 
Back
Top