PHP Boolean Type

The boolean data type in PHP is very easy to use (and why should it be difficult, it is either True or it is False).

The basic way to set a boolean value is to use the true and false keyword. Unlike other programming languages, true and false are case insensitive so you can either use true, True, TrUe, or any other variation to get the same effect.

For example:

<?
$yes = true;
$yes2 = True;

$no = false;
$no2 = False;
?>

These are all valid ways to set a variable to true or false.

PHP has some interesting ways of determining if a variable is true or false. Since PHP is a dynamically typed language, nearly any type can be evaluated as true or false. The way you can keep this straight in your head is if the variable’s value is at its default state, it will likely be evaluated as false.

To be more official, here is how PHP evaluates true or false from various values:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string “0”
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Text taken from PHP manual at: http://www.php.net/manual/en/language.types.boolean.php

Leave a Reply

Your email address will not be published. Required fields are marked *