Boolean

suggest change

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:

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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Types:
* Types
* Boolean
* Float
* Null

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR