Real World PHP

About   |   EN   |   ES

006a Data Types: Booleans

A boolean is the simplest data type. It is either true or false. Nothing else. Limiting the type to only two possible values is particularly helpful in evaluating conditionals, which is when we want to make a decision in the code. We will get to how to do that in a future chapter.

You can assign a boolean value to a variable using one of the two built-in constants: true and false.

<?php
$boolean = true;
$boolean = false;
?>

Note that the boolean constants are special in that, unlike other constants in PHP, they are case-insensitive. Thus, true, TRUE, True, and tRuE are all the same. And so are false, FALSE, False, and FaLsE.

Best Practice

Even though the boolean constants are case-insensitive, by convention, only use all lower-case when using them: true and false.

Converting to boolean

Type casting was covered in the Data Types lesson, and is as simple as inserting (bool) before the thing you want to cast. However, it is important to understand what will convert to true and what to false.

The following comes from the PHP Documentation on booleans:

When converting to bool, the following values are considered false:

  • the boolean false itself

  • the integer 0 (zero)

  • the floats 0.0 and -0.0 (zero)

  • the empty string, and the string "0"

  • an array with zero elements

  • the special type NULL (including unset variables)

  • SimpleXML objects created from attributeless empty elements, i.e. elements which have neither children nor attributes.

<?php
// The following will convert to false:
(bool) false;
(bool) 0;
(bool) 0.0;
(bool) -0.0; // Odd
(bool) "0"; // This one is surprising
(bool) array();
(bool) null;
(bool) simplexml_load_string('<p></p>'); // Also surprising
?>

A few of these may not make sense or may feel weird. We just live with the weirdness, and remember that these are the cases when casting to a boolean will return false.

Everything else will cast to true: any positive number, any negative number, and any string that is not empty or "0," etc.


Resources


Challenges

Try casting to a boolean

Using the var_dump() method, pass it the cast statements mentioned above and see what is output by PHP.

<?php
var_dump((bool) false));
var_dump((bool) 0);
var_dump((bool) 0.0);
var_dump((bool) -0.0); 
var_dump((bool) "0"); 
var_dump((bool) array());
var_dump((bool) null);
var_dump((bool) simplexml_load_string("<p></p>")); 
?>

Next, try some things that should cast to true.