PHP Booleans

Any programmable machine computes depending on the truth values. In computer programming, the truth values can be either True or False. True or False also represented by 1 and 0. Booleans are the simplest data type in computer programming.

PHP Booleans

In PHP, Boolean values are represented by True and False. In some cases, you can use 1 and 0 as truth values. PHP boolean keywords (True and False) are case-insensitive. That means you can express the booleans as following ways,

$bool1 = True; // this is correct
$bool2 = FALSE; // this is also correct
$bool3 = TrUe; // this is also

PHP Booleans use cases

In general, booleans are used to maintain the program control structure. It is typically used with the operators and expression using comparison operators to control the code blocks, which block should be executed under a certain condition.

Any non-zero component is accepted as true and only zero and False are accepted as False. In PHP, blank or empty arrays are also returned as False;

  • FALSE itself is False.
  • Integer type 0 and -0 is False.
  • Empty arrays return False.
  • An empty string also returns False.
  • The rest of the non-zero values are accepted as True including negative integers.

You can check the boolean values by the following;

    var_dump((bool) "");  // false
    var_dump((bool) 1); // true
    var_dump((bool) 1.1); // true
    var_dump((bool) -1); // true
    var_dump((bool) 0); // false
    var_dump((bool) -0); // false
    var_dump((bool) False); // false
    var_dump((bool) True); // true
    var_dump((bool) TrUe); // true


In most basic cases, booleans are used in conditions and loops for controlling the code execution;

    $num = 6;
    // booleans in if condition
    if($num == 6) {
        // code to be executed
        /* and this block will be executed
           becasue $num is exacly equal to 6
           which returns True */
    // booleans in loops
    while($num < 10) {
        echo $num++ . "\n";

Example Explanation

Here how we can use booleans in if-else and loops to control the executions. In the code above, we have $num variable with a value 6. Then we checked the value of $num in the if condition if it is 6 or not. As it is 6, the condition will return True, then the if block will be executed. We can check the comparison boolean value also using var_dump function;

$num = 6
var_dump((bool) ($num == 4)); // returns false
var_dump((bool) ($num == 6)); // returns true

We will learn more about if-else, loops with booleans in the later chapters.