A Boolean represents two possible states: TRUE or FALSE. Booleans are the core of all logic in programming—they allow your code to make decisions, run loops, and validate data.
Assigning a boolean value is simple. Note that the keywords true and false are NOT case-sensitive in PHP, but lowercase is the industry standard.
<?php
$isVisible = true;
$hasError = false;
?>
Most of the time, you don't create booleans manually; they are the result of a comparison using operators like ==, >, or <.
<?php
$x = 10;
$y = 5;
var_dump($x > $y); // Outputs: bool(true)
var_dump($x == $y); // Outputs: bool(false)
?>
An essential concept in PHP is knowing which values automatically convert to FALSE when used in a logical test (like an if statement). These are known as "Falsy" values.
The following values are considered FALSE:
false itself.0 (zero).0.0 (zero)."".[].NULL.Everything else is considered TRUE.
<?php
$name = "";
if ($name) {
echo "This will not run because empty string is false.";
}
?>
You can use the is_bool() function to check if a variable specifically contains a boolean value.
<?php
$active = true;
var_dump(is_bool($active)); // Outputs: bool(true)
?>
"0". In some languages, any non-empty string is true, but in PHP, a string containing only a zero is treated as false.