Skip to content
Tutorials Center
My learning

Topics

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.

PHP
$active = true;
if ($active) { echo "on"; }
var_dump((bool) "0");   // false

Try it

PHP What counts as false

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.

PHP Printing booleans and parsing text

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

PHP
$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 true prints 1 and echo false prints an empty string. Use var_export() or var_dump() to see the word, and json_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) understands 1, true, on, yes and their opposites; add FILTER_NULL_ON_FAILURE to 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 + true is 2. This is legal but rarely a good idea.
  • Strict typing. bool parameters accept only booleans in strict mode; in weak mode scalars are coerced. See strict_types.
  • Functions that return false on failure (strpos(), file_get_contents()) can also return a legitimate falsy value such as 0 or "". Compare with === or !==.
  • bool vs true/false types. PHP 8.2 allows true, false and null as standalone types, in addition to bool.
  • Nullable booleans (?bool) give you "yes, no, unknown", which if ($x) collapses into two cases.