OneBite.Dev - Coding blog in a bite size

Declare A Boolean In PHP

Code snippet for how to Declare A Boolean In PHP with sample and detail explanation

Booleans play an essential role in programming. This article aims to teach you how to declare a boolean in PHP in a simple and comprehendible manner.

Code snippet for Declaring a Boolean in PHP

In PHP, declaring a boolean variable is quite forthright. Here is a short code snippet demonstrating this:

<?php
    $var = TRUE; // a boolean
?>

Code Explanation for Declaring a Boolean in PHP

The keyword <?php begins the PHP tag. This instructs the web server to interpret the code it encloses using PHP.

The next line in the code snippet $var = TRUE; declares a boolean variable.

In PHP, a boolean has only two possible values: TRUE or FALSE. In this scenario, we have a variable named $var, and we’re assigning it a boolean value of TRUE. The = is an assignment operator - it assigns the value on its right to the variable on its left.

The PHP tag ends with a ?> symbol. This tells the server that the script has ended.

A noteworthy fact about booleans in PHP is that they are not case-sensitive. Which means, it doesn’t matter if you write them in uppercase, lowercase, or a combination of both. For instance, true, True, TRUE are all equivalent and valid in PHP.

Consequently, our code could have been written like this also:

<?php
    $var = true; // a boolean
?>

All of these methods for declaring a boolean in PHP are valid, and the one you use will depend on your personal preference or coding style. In the PHP community, it’s common to use all uppercase letters for boolean values.

Hopefully, now you know how to declare a boolean in PHP, and will use it comfortably in your code.

php