Search code examples
phpif-statementcomparison

Why do some people put the value before variable in if statement?


For example, what's different from $variable === true?

<?php

if (true === $variable) {
     //
}

if (1 === intval($variable)) {
    //
}

Solution

  • They are equivalent.

    Some programmers prefer this "Yoda style" in order to avoid the risk of accidentally writing:

    if ($variable = true) {
        // ...
    }
    

    , which is equivalent to

    $variable = true;
    // ...
    

    , when they meant to write

    if ($variable === true) {
        // ...
    }
    

    (whereas if (true = $variable) would generate an obvious error rather than a potentially-subtle bug).