HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Booleans

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.


1. Declaring Booleans

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;
?>

2. Comparison Results

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)
?>

3. The "Falsy" Rule

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:

  • The boolean false itself.
  • The integer 0 (zero).
  • The float 0.0 (zero).
  • The empty string "".
  • The string "0" (This is a unique PHP quirk!).
  • An array with zero elements [].
  • The special type NULL.

Everything else is considered TRUE.

<?php
    $name = "";
    if ($name) {
        echo "This will not run because empty string is false.";
    }
?>

Checking for Booleans

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)
?>
Why Booleans Matter: Without Booleans, your website would be a static list of commands. Booleans allow you to say: "IF the user is logged in, show the Dashboard; ELSE show the Login form."
Pro Tip: When checking for truthiness, be careful with the string "0". In some languages, any non-empty string is true, but in PHP, a string containing only a zero is treated as false.

Key Points to Remember

  • A Boolean has only two values: true or false.
  • Booleans are the result of comparison operators.
  • Empty strings, the number 0, and NULL are all considered false.
  • Use is_bool() to verify if a variable is a boolean.
  • Lowercase true/false is the preferred coding style.