Filter Articles By

Yoda Conditions

posted on June 10, 2017
Development Programming

We here at Stellar Blue have adopted the WordPress PHP Coding Standards for all of our PHP programming work. Using any standard helps ensure that you are writing consistent and easily maintainable code, but there can be additional benefits to well thought out code structures such as compile time and run-time errors rather than hard to find bugs.

One element of the WordPress PHP Coding Standards that accomplishes these goals is called Yoda Conditions. They are named for the odd-sounding, reversed syntax spoken by the character Yoda from the Star Wars films. Yoda Conditions reverse the often used syntax of variable, equals operator, literal resulting in literal, equals operator, variable.

What’s the big deal?

The big deal is the fact that the PHP equality operator and assignment operator are easily mistyped, and this particular typo may not generate an error. If I intend to check if $var is equal to 5 using the code if ( $var == 5 ) { but I errantly type if ( $var = 5 ) {, the condition will always be true and the conditional statement will always execute regardless of the value of var.

Happening here what is?

The result of an assignment operation in PHP is the value that has been assigned, see the assignment operator page in the PHP manual, and any non zero number evaluates to true. Since $var = 5 returns 5 and the value 5 is truthy, the condition is true and the conditional statement executes. See the boolean type page in the PHP manual for more info on truthy and falsey literals, but you get the idea; your code may seem to be ignoring your conditional statement when in reality there is a typo.

Fix it we will, yes.

Flip the arguments and the statement becomes if ( 5 = $var ) { which shows a warning in many PHP linters so you can catch the problem before you ever try to run it. If you to execute the code it throws the error Parse error: syntax error, unexpected ‘=’ . Congratulations, you just avoided creating a bug which may not have noticed otherwise.

Spend less time tracking down bugs and more time writing dependable code by adopting this change for all conditions with the ==, !=, ===, and != operators.

…Write better code you will!

Need some help? Contact the experts today! 

Leave a Reply

Your email address will not be published. Required fields are marked *