Programming Tutorials

Booleans in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008-11-22  

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





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Constants in PHP

Malware: global $ob_starting;

PHP file upload prompts authentication for anonymous users

Booleans in PHP

PHP pages does not display in IIS 6 with Windows 2003

Installing PHP with Apache 2.x on HP UX 11i and configuring PHP with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Installing PHP with nginx-server under windows

Convert IP address to integer and back to IP address in PHP

Function to force strict boolean values in PHP

Function to return number of digits of an integer in PHP

Latest Articles (in PHP)