Summary: in this tutorial, you’ll learn about the PHP Boolean data type and the boolean values
Introduction to PHP Boolean
A boolean value represents a truth value. In other words, a boolean value can be either true
or false
. PHP uses the bool
type to represent boolean values.
To represent boolean literals, you can use the true
and false
keywords. These keywords are case-insensitive. Therefore, the following are the same as true
:
True
TRUE
And the following are the same as false
:
False
FALSE
When you use non-boolean values in a boolean context, e.g., if
statement. PHP evaluates that value to a boolean value. The following values evaluate to false
:
- The keyword
false
- The integer zero (0)
- The floating-point number zero (0.0)
- The empty string (
''
) and the string"0"
- The
NULL
value - An empty array, i.e., an array with zero elements
PHP evaluates other values to true
.
The following shows how to declare variables that hold Boolean values:
$is_submitted = false;
$is_valid = true;
Code language: PHP (php)
To check if a value is a Boolean, you can use the built-in function is_bool()
. For example:
$is_email_valid = false;
echo is_bool($is_email_valid);
Code language: PHP (php)
When you use the echo
to show a boolean value, it’ll show 1
for true
and nothing for false
, which is not intuitive. To make it more obvious, you can use the var_dump()
function. For example:
<?php
$is_email_valid = false;
var_dump($is_email_valid);
$is_submitted = true;
var_dump($is_submitted);
Code language: HTML, XML (xml)
Output:
bool(false)
bool(true)
Code language: JavaScript (javascript)
Summary
- A boolean value represents a truth value, which is either
true
orfalse
. - PHP evaluates the following values to false: false, 0, 0.0, empty string (“”), “0”, NULL, an empty array; other values are
true
.