Yoda conditions

Yoda conditions

Unlearn what you have learned you must.

Yoda conditions are conditional statement where both operand are inverted from the typical order. The constant part is placed on the left side of the statement.

Typical order condition

if ( $value == 52 ) {
 /* ... */
}

Yoda condition

if ( 52 == $value ) {
  /* ... */
}

Why would you do that ?

Imagine if you forgot one equal sign in the statement above:

Typical order condition

Typical order condition will become an assignment and set $value to 52 while returning true.

Yoda condition

Yoda condition will fail as you cannot assign a value to a constant. So you will be warned about your error.

Why would you not do that ?

Yoda conditions can be criticized as they affects readability. Reading and writing both appear less natural. Also most decent IDE will raise a warning if you assign a variable within a condition helping you to avoid that kind of error.

Please note that projects like Symfony or Wordpress include Yoda conditions in their coding standards. As stated in Symfony documentation: "Use Yoda conditions when checking a variable against an expression to avoid an accidental assignment inside the condition statement (this applies to ==, !=, ===, and !==);"