Booleans in PHP

By: Andi, Stig and Derick Viewed: 153222 times  Printer Friendly Format    


Booleans were introduced for the first time in PHP 4 and didn’t exist in prior versions. A Boolean value can be either true or false. PHP automatically converts types when needed. Boolean is probably the type that other types are most often converted to behind the scenes. This is because, in any conditional code such as if statements, loops, and so on, types are converted to this scalar type to check if the condition is satisfied. Also, comparison operators result in a Boolean value.

Consider the following code fragment:

$numerator = 1;

$denominator = 5;

if ($denominator == 0) {

print "The denominator needs to be a non-zero number\n";

}

The result of the equal-than operator is a Boolean; in this case, it would be false and, therefore, the if() statement would not be entered. Now, consider the next code fragment:

$numerator = 1;

$denominator = 5;

if ($denominator) {

/* Perform calculation */

} else {

print "The denominator needs to be a non-zero number\n";

}

You can see that no comparison operator was used in this example; however, PHP automatically internally converted $denominator or, to be more accurate, the value 5 to its Boolean equivalent, true, to perform the if() statement and, therefore, enter the calculation. Although not all types have been covered yet, the following table shows truth values for their values.

Data Type False Values True Values
Integer 0 All non-zero values
Floating point 0.0 All non-zero values
Strings

Empty strings ()""
The zero string ()"0"

All other strings
Null  Always  Never
Array

If it does not contain any elements

If it contains at least one element

Object Never Always
Resource Never Always


Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial