I often see if structures being coded like this:
if (true == a)
if (false == a)
Why do they put the constant value first and not the variable? as in this example:
if (a == true)
if (b == true)
This is called yoda syntax or yoda conditions.
It is used to help prevent accidental assignments.
If you forget an equals sign it will fail
if(false = $a)
fails to compile
if($a = true)
assigns the value of true
to the variable $a
and evaluates as true
The Wordpress Coding Standards mention this specifically:
if ( true == $the_force ) {
$victorious = you_will( $be );
}
When doing logical comparisons, always put the variable on the right side, constants or literals on the left.
In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true. If the statement were the other way around ( $the_force = true ), the assignment would be perfectly valid, returning 1, causing the if statement to evaluate to true, and you could be chasing that bug for a while.
A little bizarre, it is, to read. Get used to it, you will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With