Wednesday, November 16, 2011

How to Create Booleans in PHP

booleans in php

Summary: In this tutorial I will explain you how to create Boolean variables in PHP, where they are used, how to use true, false and null and lastly there is a video tutorial on How to Create Booleans in PHP in both English and Hindi.


Booleans are special data types used in making decisions, their values can either be true, false or null. You store the state of process in booleans, for example if the task is completed set the flag to true and if not set the task to false and do the task again.

Consider this real life example, two boys are competing in a race and you need to keep track of it, so what you will do is assign someone on the crossing line with flag, then when the boy who reach the track first will see the winners flag and other will not .

In terms of PHP this will be like this: Initialize two boolean variable with null, say $boy1 = null and $boy2 = null, then say boy1 wins the race, the situation will be like this : $boy1 = true and $boy2 = false. So this is the use of booleans in programming.


    // Initialize two boolean variables
    $boy1 = null;    
    $boy2 = null;
    // If boy1 wins the race, set boy1 to true and boy2 to false 
    $boy1 = true;    
    $boy2 = false;

In PHP , you should not to include quotes while writing booleans values, if you put a quotes then they will become string rather than booleans.


    // Putting quotes around boolean values will convert them into strings
    $boy1 = "null";    
    $boy1 = "true";    
    $boy2 =" false";

Booleans values, true, false and null are case insensitive, so writing this is legal:


    // Boolean values are case insensitive
    $boy1 = NULL;    
    $boy1 = True;    
    $boy2 = faLse;

Use of booleans will become much clear to you when in coming chapters I will discuss about conditional statements and boolean functions in PHP.

Booleans in PHP [Video tutorial in English]

Booleans in PHP [Video tutorial in Hindi]

This is the sixth chapter in which I explained you How to create Booleans in PHP, in the next chapter I will explain you How to create Arrays in PHP.