Is True (In PHP)?

12,540

Solution 1

The first is better if you simply want a truthy-check.

  • It's shorter and thus easier to read
  • Even though it doesn't explicitly state equality to true, it's rather obvious what it does

The explicit type check with === is a better choice when you must be sure of the type of the data (eg. input validation or such)

Solution 2

The two, doesn't really do the same thing. if ($boolean) is more of a 'not false' statement, asserting true for anything not false, 0, or null. If you set $boolean = 'false', the statement will be true.

Assuming that it is a pure boolean comparison you want, you should use the latter case explicity checking that the contents of the variable is in fact a boolean.

Solution 3

Using if ( $boolean === true ) {} when you know that $boolean is a boolean is redundant, therefore I wouldn't consider it good practice. This can be further reinforced by naming variables with names that show their booleaness, e.g. $isCool.

Share:
12,540
daGrevis
Author by

daGrevis

Hacker working with Clojure, Python, ReactJS and Docker. Enjoys r/unixporn and r/vim. Loves DotA 2, blues rock and gym. Really loves his girlfriend. https://twitter.com/daGrevis https://github.com/daGrevis https://news.ycombinator.com/user?id=daGrevis https://lobste.rs/u/daGrevis http://www.linkedin.com/in/daGrevis

Updated on July 20, 2022

Comments

  • daGrevis
    daGrevis almost 2 years

    What to use better?

    if ( $boolean ) {}
    

    ...or:

    if ( $boolean === true ) {}
    

    Both work, both check that $boolean is set to 'true'. The second one also checks $boolean's type.

    If we assume that $boolean holds value that's boolean, what option should I use?

  • Jürgen Thelen
    Jürgen Thelen about 13 years
    +1 for mentioning both cases.