Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)) {
    //
}
like image 844
Chan Avatar asked Aug 27 '14 02:08

Chan


1 Answers

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).

like image 171
ruakh Avatar answered Oct 04 '22 14:10

ruakh