phpif-statementcode-standardspsr-12

Not operator or Strict comparison on false?


What's the best practice for writing if-statement on boolean value?

function foo(boolean $bar)
{
    if ($bar === false) // ...
    // or
    if (!$bar) // ...
}

With a Not operator it's more compact, but you may not notice this operator while reading a code.

And why do some coders write in Yoda style like false === $bar ?


Solution

  • The obvious reason is in case you don't have Boolean return value and need to differentiate between other falsy values (0, false, null, "0", etc). For example when using strrpos() you might get false which is different than 0.

    As for the ugly Yoda style, that is to avoid mistakes such as $bar = false instead of $bar == false. You would get error if you tried false = $bar and notice it straight away.