Monday, March 16, 2009

Boolean datatype in Php

The boolean datatype in php in considered specially. The boolean datatype expresses the truth value which can be either TRUE or FALSE.

Confusion may come while your print boolean datatype and while converting the value of boolean datatype variable.

When converting to boolean type the following values are considered as FALSE.

1)the boolean FALSE itself
2)the integer 0 (zero)
3)the float 0.0 (zero)
4)the empty string, and the string "0"
5)an array with zero elements
6)an object with zero member variables (PHP 4 only)
7)the special type NULL (including unset variables)
8)SimpleXML objects created from empty tags

Except the above 8 types all converted boolean type are considered as TRUE even a -1.

Whenever you print any boolean FALSE value it will print NULL and whenever you print any boolean TRUE value it will print 1 but never think that FALSE is NULL and 1 is a constant for TRUE. NULL is boolean value that indicates FALSE and 1 is a boolean value that indicates TRUE.

Symbolic constants are specifically designed to always and only reference their constant value. But booleans are not symbolic constants, they are values which means either true or false. So operate them like symbolic constants may have problems. Like (true+true) will print 2 but two boolean variable containing truth value TRUE adding will print 1.


<html>
<body>
<?php
$booleanTType=True;
$booleanFType=False;
echo 'Output of "(True)":'.$booleanTType ;
echo "<br />";
echo 'Output of "(False)":'. $booleanFType ;
echo "<br />";
echo (true+true);
echo "<br />";
echo 'Output of "(True+True)":'.($booleanTType+$booleanTTypes);
echo "<br />";
echo 'Output of "(False+False)":'.($booleanFType+$booleanFTypes) ;
?>
</body>
</html>

Output
Output of "(True)":1
Output of "(False)":
2
Output of "(True+True)":1
Output of "(False+False)":0
Related Documents
Datatypes in Php
Integer and floating point number in Php
Variables in PHP
Magic constants in php

No comments:

Post a Comment