Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is True (In PHP)? [closed]

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?

like image 639
daGrevis Avatar asked Apr 24 '11 18:04

daGrevis


People also ask

Is true in PHP?

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.

Is true equal to 1 in PHP?

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.

Is null true or false PHP?

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.

What does ?: Mean in PHP?

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.


3 Answers

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)

like image 165
Jani Hartikainen Avatar answered Oct 08 '22 08:10

Jani Hartikainen


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.

like image 45
Jakub Hampl Avatar answered Oct 08 '22 08:10

Jakub Hampl


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.

like image 1
Jon Skarpeteig Avatar answered Oct 08 '22 09:10

Jon Skarpeteig