PHP Reference ยท Types and Type Handling
The PHP bool type
Reference for the PHP bool type: true and false, the values that convert to false, boolean casts, filter_var for parsing, and comparison pitfalls.
A bool holds one of two values, true or false. The keywords are case-insensitive (TRUE, True), but lowercase is the universal style. Booleans are the result of comparisons and the input of every condition in if, while, for, the ternary operator and the logical operators.
When a non-boolean value is used where PHP expects a boolean, it is converted. Only a short list of values converts to false; everything else is true, including some values that may surprise you, such as the string "0.0" and an empty-looking object.
$active = true; if ($active) { echo "on"; } var_dump((bool) "0"); // false
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$flag = true; $flag = false; $flag = (bool) $value; // or (boolean) $flag = boolval($value);
Values that are false when converted: false, the integers 0 and -0, the floats 0.0 and -0.0, the empty string "", the string "0", the empty array [], and null. Every other value is true. (NAN is true.)
Usage notes
- Printing:
echo trueprints1andecho falseprints an empty string. Usevar_export()orvar_dump()to see the word, andjson_encode()for JSON booleans. - The string
"0"is falsy but"0.0"and" "are not. User input that arrives as strings needs explicit parsing:filter_var($v, FILTER_VALIDATE_BOOLEAN)understands1,true,on,yesand their opposites; addFILTER_NULL_ON_FAILUREto tell "no" from "invalid". - Empty objects are truthy. An object is always
true(SimpleXML objects with no content are a historical exception). - Arithmetic converts to int:
true + trueis2. This is legal but rarely a good idea. - Strict typing.
boolparameters accept only booleans in strict mode; in weak mode scalars are coerced. See strict_types. - Functions that return
falseon failure (strpos(),file_get_contents()) can also return a legitimate falsy value such as0or"". Compare with===or!==. boolvstrue/falsetypes. PHP 8.2 allowstrue,falseandnullas standalone types, in addition tobool.- Nullable booleans (
?bool) give you "yes, no, unknown", whichif ($x)collapses into two cases.