PHP Boolean


Example

Boolean is a type, having two values, denoted as true or false.

This code sets the value of $foo as true and $bar as false:

$foo = true;
$bar = false;

true and false are not case sensitive, so TRUE and FALSE can be used as well, even FaLsE is possible. Using lower case is most common and recommended in most code style guides, e.g. PSR-2.

Booleans can be used in if statements like this:

if ($foo) { //same as evaluating if($foo == true)
    echo "true";
}

Due to the fact that PHP is weakly typed, if $foo above is other than true or false, it's automatically coerced to a boolean value.
The following values result in false:

  • a zero value: 0 (integer), 0.0 (float), or '0' (string)
  • an empty string '' or array []
  • null (the content of an unset variable, or assigned to a variable)

Any other value results in true.

To avoid this loose comparison, you can enforce strong comparison using ===, which compares value and type. See Type Comparison for details.

To convert a type into boolean, you can use the (bool) or (boolean) cast before the type.

var_dump((bool) "1"); //evaluates to true

or call the boolval function:

var_dump( boolval("1") ); //evaluates to true

Boolean conversion to a string (note that false yields an empty string):

var_dump( (string) true ); // string(1) "1"
var_dump( (string) false ); // string(0) ""

Boolean conversion to an integer:

var_dump( (int) true ); // int(1)
var_dump( (int) false ); // int(0)

Note that the opposite is also possible:

var_dump((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)

Also all non-zero will return true:

var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)