PHP Boolean Data Type


Definition and Usage

This is one of the scalar data types in PHP. A boolean data can be either TRUE or FALSE. These are predefined constants in PHP. The variable becomes a boolean variable when either TRUE or FALSE is assigned.

Syntax

<?php
//Literal assignment of boolean value to variable
$var=TRUE;
?>

Result of echoing TRUE value displays 1 while for FALSE it shows nothing. Using var_dump() function displays bool as type with value

Boolean constants are not case sensitive. That means TRUE is equivalent to true and FALSE is similar to False

Logical operators return boolean value

<?php
$gender="Male";
echo ($gender=="Male");
?>

Casting

Any data type can be explicitly converted to boolean with the help of casting operator (bool) or (boolean), although, most of the times, conversion is done automatically whenever required.

PHP Version

This description is applicable to all versions of PHP.

Following example shows use of echo and var_dump() to diplay boolean value

Example

 Live Demo

<?php
$var=TRUE;
echo $var . "
"; var_dump($var); $var1=false; echo $var1; var_dump($var1); ?>

Output

This will produce following result −

1
bool(true)
bool(false)

Example shows boolean result of logical expression

Example

 Live Demo

<?php
$var=10;
var_dump($var>10);
var_dump($var==true);
?>

Output

This will produce following result −

bool(false)
bool(true)

Example shows use of casting operator

Example

 Live Demo

<?php
$var=10;
$var1=(bool)$var;
var_dump($var1);
//0 and -0 return false
$var=0;
$var1=(bool)$var;
var_dump($var1);
//empty string returns false
$var="PHP";
$var1=(bool)$var;
var_dump($var1);
$var="";
$var1=(bool)$var;
var_dump($var1);
//empty array is case to false
$var=array(1,2,3);
$var1=(bool)$var;
var_dump($var1);
$var=array();
$var1=(bool)$var;
var_dump($var1);
?>

Output

This will produce following result −

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

Updated on: 19-Sep-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements