Boolean Data Type in PHP

Introduction

In this article I will explain Boolean data types in PHP. Boolean is the simplest type. A Boolean expression is a true type value. It is used in control structures like for testing portions of an if statement. It can be either TRUE or FALSE.

Types of the Boolean Value

Data Type True Value False Value
Integer All the non-zero values 0
Floating Point All the non-zero values 0.0
Null Never Always
Array If it is contains only one elements Does not contains any elements
String All other string Empty string ()""
The Zero string ()"0"
Object Always Never
Resource Always Never

Example

<?php 

$height=100; 

$width=50; 

if ($width == 0) 

echo "The width needs to be a non-zero number"

?>

In the above example, it would be false and, therefore, the echo statement will never execute.

<?php

$height=100; 

$width=50; 

if ($width)

{

 echo "The area of the rectangle is  

($height*$width)";

else

{

echo "The width needs to be a non-zero number";

?>

This example does not compare $height and $width. PHP automatically converted the $width value of 50 to Boolean. The calculated area of the rectangle is displayed inside the if() statement.

Output

Data type boolean.jpg

Converting to Boolean

<?php

var_dump((bool"");       

var_dump((bool)  1);        

var_dump((bool)  -2);      

var_dump((bool) "raaa");    

var_dump((bool) 2.3e5);    

var_dump((bool) array(12));

var_dump((bool) array());  

var_dump((bool) "false"); 

?>

Output

Converting the boolean data type.jpg