Datatypes in PHP - Boolean : Tutorial

1. Boolean data type

Boolean data type can have only two values. TRUE or FALSE

We can assign a variable boolean values,
$flag = TRUE; //flag holds boolean value True
Boolean values TRUE and FALSE are Case in-sensitive.

Booleans are mostly used to compare two values with if statements,
$var1 = 20;
$var2 = 20;

== operator is used to test equality of the two variables.

If both values are same, If condition returns True, else False

if($var1 == $var2) {
 echo "Both values are equal!";

if($var1 > $var2) {
 echo "var1 is greater then var2 values are equal!";

Both values are equal!

Following values are considered as FALSE:
- Boolean FALSE itself
- Integer 0
- Float 0.0
- Empty string ""
- String "0"
- Array with zero elements
- Object with zero member variables
- Variables which are not set(e.g $a)

Following values are considered as TRUE:
- Boolean TRUE itself
- Integer other then zero
- Floats other then zero
- Non-Empty string ""
- Array with non-zero elements
- Object with non-zero member variables
- Variables which certain data (ie not null)

Note :
- This function var_dump() displays structured information about expressions. The output includes its type and value.
- We can convert other variables to Boolean by typecasting it with (bool) as follows,
 $boolVal = (bool) $variable;

Examples of Boolean Typecasting and resulting values :

$a = NULL;

var_dump((bool) NULL);      // FALSE
var_dump((bool) "");        // FALSE
var_dump((bool) 0);   	    // FALSE
var_dump((bool) 0.0);       // FALSE
var_dump((bool) "0");       // FALSE
var_dump((bool) $a);   	    // FALSE if $a is not set
var_dump((bool) array());   // FALSE

echo <br>;

var_dump((bool) 123);           // TRUE
var_dump((bool) -123);          // TRUE
var_dump((bool) "message");     // TRUE
var_dump((bool) 1.23e5);        // TRUE
var_dump((bool) array(123));    // TRUE
var_dump((bool) "false");       // TRUE

bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(true) bool(true) bool(true) bool(true) bool(true) bool(true)