PHP Bool or PHP Boolean refers to the value that is already assigned to the variable. It can be true or false values. And we are using it to detect the coming data, check calculation values or detect variable values, The important thing is it should give us a true or false value.

The boolean values are case-insensitive ( true or false ). PHP supports bool type as a defined word for variables.

PHP Boolean Data Type

PHP boolean values can be written as case-insensitive like the below

  • True – False
  • true – false
  • TRUE – FALSE

When using the casting for an empty some other data types to boolean values it will give us no positive value.

  • When casting an empty string it will give us a false value : ( bool ) “” the result is false.
  • Negative integers will give us a positive boolean value: : ( bool ) -1 the result is true.
  • Casting a zero value in a string will show us a false value : ( bool ) “0” the result is false.
  • Any positive integer started from 1 or -1 with boolean casting will show a true positive boolean value.
  • Casting an empty array is a false value in the boolean data type.

So basically, any non-zero value shows a positive boolean otherwise it is a false value, consider all negative values also are positive boolean values. Also the same in a string type, any non-empty value shows a positive boolean, otherwise, it is a false value. And in the array type, any empty array shows a false value otherwise it is a positive value.

PHP Boolean Examples

Boolean and Integer Checking

A non-zero integer data type is giving us a true positive boolean value when we detect it with a double equal operator.

<?php 
   var_dump( 0 == false ); // bool(true)
   var_dump( 0 === false ); // bool(false)
?>

But, the second triple equal operator, gave us a false value. The reason is the second detection was for the value and the data type. And there we have a boolean data type and an integer data type. Otherwise, the first detection was only for the value. So it gave us a positive boolean value.

Integer and String Checking

In the following example, we need to check if a string contains some value equality with a zero integer value. As we mentioned before a negative boolean value has equality with zero in values.

<?php 
   var_dump( 0 == "Hello"); // bool(false)
   var_dump( 0 === (bool) "CodedTag.com" ); // bool(false)
?>

Converting to PHP Boolean

To convert to boolean data type from another data type we have to use casting. It starts with the value and before it uses cast like this (bool).

For example

<?php $boolean = (bool) "CodedTag.com"; ?>

And to validate if the current variable has a bool data type value, use the following PHP predefined callback.

<?php 
  is_bool( $var );
?>

To learn more details go to the PHP data Types tutorial.