PHP Lessons - Lesson 5 - PHP Logical Variables
So far, we’ve learned that PHP supports numbers and strings. But this is not all—this lesson introduces another type of variable: Boolean variables. They are called Boolean because they are used to build logical structures in code.
Let’s say you want to drink water from a glass. If there’s too little water, you won’t quench your thirst. If there’s too much, you might spill it when tilting the glass. So, depending on the condition, you’ll either pour more water in or take some out.
This logic could be described like this:
$water_amount = 100;
$not_enough_water = TRUE;
IF $not_enough_water
THEN $water_amount = $water_amount + 20;
In this case, $not_enough_water
is a Boolean variable that can hold only two values: TRUE
or FALSE
. That’s it—no in-between.
Now, this isn’t valid PHP code—it’s just pseudo-code. In PHP, this would look like:
<?php
$water = 100;
$not_enough_water = TRUE;
if($not_enough_water){
$water = $water + 20;
}
?>
We’ll dive deeper into the if
statement later. For now, let’s focus on TRUE
and FALSE
.
People often use 1 and 0 instead of TRUE and FALSE. But why bother using TRUE and FALSE at all?
Remember how integer variables take up half the memory of floating-point numbers? Boolean variables (TRUE/FALSE) are even more efficient:
- They take 4 times less memory than integers
- They take 8 times less memory than floats
So, when possible, it's a good idea to use Boolean values to save memory.
You might think: "But I have 8 GB of RAM—who cares?" Imagine you have a website with 1000 integer variables that could instead be Boolean. If each request loads 4 MB of these variables, 100 simultaneous users would require 400 MB. With Boolean variables, that becomes only 100 MB—a savings of 300 MB!
And what happens when Booleans are used in calculations? PHP handles this smoothly:
<?php $var1 = TRUE; $var2 = TRUE + 1; echo $var2; // Output: 2 ?>
PHP will automatically convert the Boolean to a number: TRUE becomes 1 and FALSE becomes 0. So don’t worry about type compatibility in such cases.