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?
Definition and UsageThe is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.
The boolean values are called true and false in php. In the case of true , the output is 1 . While with the false , it does not show any output. It is worth noting that the browser always renders these values in strings.
NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0 , "0" , "" , and false . Show activity on this post. Null is nothing, False is a bit, and 0 is (probably) 32 bits.
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
The first is better if you simply want a truthy-check.
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)
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With