Booleans help us decide if something is true or false in our code. They make choices simple and clear.
0
0
Boolean type behavior in PHP
Introduction
Checking if a user is logged in or not.
Deciding if a form input is valid.
Turning features on or off in a program.
Controlling loops that run only while a condition is true.
Making simple yes/no decisions in your code.
Syntax
PHP
<?php $variable = true; // or false ?>
Boolean values in PHP are true and false (all lowercase).
They are often used in conditions like if statements to control the flow.
Examples
This checks if it is raining. If true, it tells you to take an umbrella.
PHP
<?php $is_raining = true; if ($is_raining) { echo "Take an umbrella."; } ?>
This uses
false and the ! (not) operator to deny access.PHP
<?php $has_access = false; if (!$has_access) { echo "Access denied."; } ?>
Boolean can come from comparisons. Here, 5 > 3 is true.
PHP
<?php $logged_in = (5 > 3); // true because 5 is greater than 3 var_dump($logged_in); ?>
Sample Program
This program decides what to do based on if it is sunny and if it is the weekend. It uses boolean values and logical operators.
PHP
<?php // Simple program to show boolean behavior $is_sunny = true; $is_weekend = false; if ($is_sunny && $is_weekend) { echo "Go to the park!"; } elseif ($is_sunny && !$is_weekend) { echo "Go to work, but enjoy the sun."; } else { echo "Stay inside."; } ?>
OutputSuccess
Important Notes
In PHP, many values can be converted to boolean automatically, like 0 is false, and any non-zero number is true.
Use var_dump() to see the exact boolean value during debugging.
Remember that strings like "" (empty) are false, but "0" (string zero) is also false in PHP.
Summary
Booleans are simple true or false values used to make decisions in code.
They help control what your program does by checking conditions.
Logical operators like && (and), || (or), and ! (not) work with booleans.