Original question
i read sometime ago in an article i can't find that when doing a comparison the order matters for some reason.
i couldn't find any information on the subject of the order of comparing in PHP.
it obviously won't make a dramatic change but i am curious to know if there is any merit to this.
throughout the project i am working on the comparison is done as $x === true
.
is there any difference in doing the comparison in the opposite order, as in true === $x
?
Conclusion
Apparently what i referred to in the original question is a programming style called "Yoda conditions".
This wiki page gives a good explanation about this style.
This answer made me understand the concept, just note there is a small mistake there.
Here's my take on it:
The main reason to use this style is to avoid an accidental assignment with =
when you meant to compare with ==
.
if you want to check if a variable loosely has the same value as what you compare it to, use:
if(false == $var) // evaluates to true if $var is equal to false
over
if($var == false) // evaluates to true if false is equal to $var
to prevent
if($var = false) // assigns false to $var and evaluates to false
while
if(false = $var) // is a syntax error
if you want to check if a variable strictly has the same value as what you compare it to, use:
if(false === $var) // evaluates to true if $var is identical to false
over
if($var === false) // evaluates to true if false is identical to $var
it doesn't matter in the context of using Yoda style or not as this isn't really an issue with strict comparison because it's pretty hard to confuse
=
with===
but if you use it for==
then also use it for===
to be consistent.
All in all, I think the merit of Yoda notation lies in the emphasized distinction it makes between comparison and assignment in a condition.