Why does WordPress reverse conditional statements?

In WordPress’ core code, you often see this:

if (1 == $someVar)

as opposed to this:

Read More
if ($someVar == 1)

I don’t know if the first way is a WordPress-centric style of coding, but I’ve only noticed it in WP code (either core or 3rd-party code).

Related posts

Leave a Reply

1 comment

  1. This coding style is known as a Yoda Condition, and it’s nothing specific to WordPress. I’ve used the same style in C++, C#, and even JavaScript code.

    The main benefit of a Yoda Condition is that it prevents accidental value assignment from a typo. Consider the following (often-seen-in-the-wild) typo:

    if ( $some_variable = 1 ) {
        // ...
    }
    

    This will always evaluate to true, but has the additional consequence of assigning the value 1 to $some_variable. Sometimes this is intentional, though. In WordPress specifically, you’ll often see things like:

    if ( $post = some_function( $_POST['id'] ) ) {
        // ...
    } else {
        // ...
    }
    

    The point of this code is to assign a new value to the $post variable, and it works because the some_function() being used will return false on error.

    Yoda Conditions (reversing the order of the == equality operator) protect you from accidentally assigning values when you didn’t mean to. If you make a mistake and only put one = in the code, you’ll get an error because you can’t assign to a regular value:

    if ( 1 = $some_variable ) {
        // ...
    }
    

    Like I said, this is not unique to WordPress, or even to PHP, however it is part of the required WordPress coding standards. If you’re writing a plugin or theme for general distribution, or contributing to core, you need to know both what Yoda Conditions are and how to use them