PHP Basics: Boolean Logic Tutorial

Hi there PHP fans! (lol I sound like an American sports commentator). Ok we’re going to take a look at PHP Boolean logic, it’s a tutorial, so we’ll take you through it simply and give you some examples. Easy peasy! – It won’t take long.

PHP Boolean Type

Booleans are the simplest php ‘type’. A boolean expresses a ‘truth’ value. It can only be ‘TRUE’ or ‘FALSE’, nothing else!

PHP Boolean History

Boolean was introduced in PHP version 4, all versions which superseed PHP4 will be able to use BOOLEAN’s.

Boolean Syntax (how to write a boolean)

Specifying a Boolean is a literal use of the keywords TRUE or FALSE. Both – they aren’t case sensitive.

Boolean Example Code

<?php
$var1 = TRUE; // assign the value TRUE to $var1
?>

Typically boolean’s are used to control other functions, events, as they are a based on logic. Like ‘on’ or ‘off’ switches.

Example of PHP Boolean Test from the PHP.net Website

<?php
// == is an operator which tests equality and returns a boolean

if ($action == "show_version") {
    echo "the vesrion is 1.23";
}
// this is not necessary
if ($show_separators == TRUE) {
   echo "<hr> \n";
}
// we can do it this way because of the boolean test, it's simple!
if ($show_separators) {
   echo "<hr>\n";
}
?>

I like this example, because it really shows you how you are saving time, and gives a good example of useage.

Boolean Values which are considered ‘FALSE’

  • FALSE
  • integerĀ 0 (zero)
  • float value 0.0 (zero)
  • empty string, and the string “0″ (zero in quotes)
  • array with zero elements (not that you would really use this over something else)
  • an object with zero member variables
  • NULL

All other values are considered TRUE.

Leave a Reply