What is Boolean in PHP: Simple Explanation and Examples
boolean is a data type that can hold only two values: true or false. It is used to represent simple yes/no or on/off states in your code.How It Works
Think of a boolean in PHP like a light switch that can only be either on or off. It has just two possible states: true (on) or false (off). This makes it perfect for decisions in your code, such as checking if a condition is met or not.
When PHP evaluates expressions, it often converts values to boolean to decide what to do next. For example, if you ask PHP to check if a number is greater than another, the result is a boolean: true if it is, or false if it isn’t. This simple yes/no answer helps your program choose the right path.
Example
This example shows how to use booleans in PHP to check if a number is even or odd.
<?php $number = 4; $isEven = ($number % 2 == 0); if ($isEven) { echo "The number $number is even."; } else { echo "The number $number is odd."; } ?>
When to Use
Use booleans in PHP whenever you need to make decisions or control the flow of your program. For example, you can use booleans to:
- Check if a user is logged in (
trueif logged in,falseif not) - Control loops that run only while a condition is
true - Validate form inputs by checking if they meet certain rules
- Toggle features on or off in your application
Booleans keep your code simple and clear by representing conditions with just two states.
Key Points
- A boolean in PHP can only be
trueorfalse. - It is used to represent simple yes/no or on/off conditions.
- PHP automatically converts many values to boolean when checking conditions.
- Booleans help control the flow of your program with
ifstatements and loops.