PHP Booleans
What Is a Boolean?
In simple terms: A boolean is a value that can only be true or false. It answers yes/no questions: Is the user logged in? Is the item in stock? Did the payment succeed?
Technically: bool is a scalar type with exactly two values, true and false. Booleans are produced by comparisons and logical operations, and they control the flow of a program through if statements, loops, and the ternary operator.
Why Booleans Matter
Every decision a program makes is based on a condition that ultimately evaluates to true or false. Understanding booleans — and especially how PHP converts other values to booleans — is essential for writing conditions that behave as intended.
Creating Booleans
Syntax
$variable = true;
$variable = false;
Example
<?php
$isLoggedIn = true;
$hasUnpaidInvoices = false;
var_dump($isLoggedIn);
var_dump($hasUnpaidInvoices);
Output
bool(true)
bool(false)
true and false are case-insensitive constants: TRUE, True, and true are all the same value. Modern coding standards (PER Coding Style) require the lowercase form.
Booleans From Comparisons
Most booleans in real code are not written directly — they are the result of comparisons.
Example
<?php
$age = 20;
$cartTotal = 450;
$role = "editor";
$isAdult = $age >= 18;
$qualifiesForFreeShipping = $cartTotal >= 500;
$canEdit = $role === "editor" || $role === "admin";
var_dump($isAdult);
var_dump($qualifiesForFreeShipping);
var_dump($canEdit);
Output
bool(true)
bool(false)
bool(true)
How It Works
$age >= 18compares two numbers and producestrue.$cartTotal >= 500producesfalse.$role === "editor" || $role === "admin"combines two comparisons with the logical OR operator||; the result istrueif either comparison is true.
Storing a condition's result in a well-named variable, such as $qualifiesForFreeShipping, makes later code read like a sentence:
if ($qualifiesForFreeShipping) {
$shipping = 0;
}
Comparison and logical operators are covered in Comparison Operators and Logical Operators.
Using Booleans in Conditions
<?php
$isMaintenanceMode = false;
if ($isMaintenanceMode) {
echo "The site is under maintenance.";
} else {
echo "Welcome!";
}
Output
Welcome!
Write if ($isMaintenanceMode) rather than if ($isMaintenanceMode == true). The variable is already a boolean, so comparing it to true adds noise without adding meaning.
Converting Values to Boolean
What Happens
When a value of another type is used where a boolean is expected — in an if, a while, with !, &&, ||, or the ternary operator — PHP converts it to a boolean automatically. You can also convert explicitly with (bool).
The Falsy Values
Only these values convert to false. Everything else converts to true.
| Value | Type | Converts To |
|---|---|---|
false | bool | false |
0 | int | false |
0.0, -0.0 | float | false |
"" (empty string) | string | false |
"0" | string | false |
[] (empty array) | array | false |
null | null | false |
(Additionally, SimpleXML objects created from empty XML elements without attributes are falsy. This is a special case of that extension.)
Values that convert to false are called falsy; all others are truthy.
Example: Surprising Truthy Values
<?php
$values = ["0", "0.0", " ", "false", [0], -1, 0.1, "00"];
foreach ($values as $value) {
echo str_pad(var_export($value, true), 10), " => ";
var_dump((bool) $value);
}
Output
'0' => bool(false)
'0.0' => bool(true)
' ' => bool(true)
'false' => bool(true)
array (
0 => 0,
) => bool(true)
-1 => bool(true)
0.1 => bool(true)
'00' => bool(true)
Why These Results Occur
"0"is falsy, but"0.0","00", and" "are truthy. Only the exact string"0"and the empty string are falsy. This special case exists because form fields and URL parameters arrive as strings, and"0"was treated like the number zero."false"is truthy. It is a non-empty string; PHP does not interpret its text.[0]is truthy. The array is not empty — it contains one element — even though that element is falsy.-1is truthy. Any non-zero number is truthy, including negative numbers.
(var_export() prints a value as valid PHP code, which shows strings with quotes so you can see the difference between '0' and 0.)
The strpos() Trap: When 0 Means Success
Many PHP functions return false on failure but can also return 0 as a valid result. Treating the result as a boolean confuses the two.
Problem
<?php
$email = "admin@example.com";
if (strpos($email, "admin")) {
echo "Admin address";
} else {
echo "Regular address";
}
Output
Regular address
Why This Is Wrong
strpos() returns the position where the search text was found. "admin" is found at position 0 — the start of the string. 0 is falsy, so the if treats a successful search as a failure. When the text is not found, strpos() returns false. Both outcomes look the same to a loose if.
Fix 1: Compare Strictly With false
<?php
if (strpos($email, "admin") !== false) {
echo "Admin address";
}
!== checks both value and type. 0 !== false is true, because an int is not identical to a bool.
Fix 2: Use a Function That Returns a Boolean (PHP 8.0+)
<?php
if (str_starts_with($email, "admin")) {
echo "Admin address";
}
PHP 8.0 added str_contains(), str_starts_with(), and str_ends_with(), which return real booleans and avoid this trap entirely.
Other Functions With the Same Pattern
| Function | Valid Result That Is Falsy | Failure Value |
|---|---|---|
strpos(), stripos(), strrpos() | 0 (found at the start) | false |
array_search() | 0 (found at index 0) | false |
file_get_contents() | "" (empty file) | false |
fgets() | "0" (a line containing only 0, without newline) | false |
Rule: when the PHP manual says a function "returns false on failure", check the result with === false or !== false.
Converting Booleans to Other Types
Example
<?php
echo "true as string: '" . true . "'\n";
echo "false as string: '" . false . "'\n";
var_dump((int) true, (int) false);
var_dump(true + true);
var_dump(json_encode(['active' => true]));
Output
true as string: '1'
false as string: ''
int(1)
int(0)
int(2)
string(15) "{"active":true}"
Explanation
- When converted to a string,
truebecomes"1"andfalsebecomes an empty string. This is whyecho false;prints nothing. - When converted to an integer,
trueis1andfalseis0, sotrue + trueequals2. json_encode()keeps booleans as JSONtrue/false, which JavaScript reads as real booleans.
Because echo shows false as nothing, use var_dump() or var_export() to inspect booleans:
<?php
$result = false;
echo "Result: " . var_export($result, true);
Output
Result: false
Converting Text Input to Booleans Correctly
Form checkboxes, query parameters, configuration files, and environment variables often represent booleans as strings such as "yes", "on", "1", "true", or "false". A plain (bool) cast does not understand these words:
<?php
var_dump((bool) "false"); // bool(true) — wrong for this purpose
Use filter_var() With FILTER_VALIDATE_BOOLEAN
<?php
$inputs = ["true", "false", "yes", "no", "on", "off", "1", "0", "", "maybe"];
foreach ($inputs as $input) {
$result = filter_var($input, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
printf("%-7s => %s\n", "'$input'", var_export($result, true));
}
Output
'true' => true
'false' => false
'yes' => true
'no' => false
'on' => true
'off' => false
'1' => true
'0' => false
'' => false
'maybe' => NULL
How It Works
FILTER_VALIDATE_BOOLEANreturnstruefor"1","true","on", and"yes"(case-insensitive), andfalsefor"0","false","off","no", and"".- Without
FILTER_NULL_ON_FAILURE, unrecognized values such as"maybe"also returnfalse, so you cannot distinguish "no" from "invalid input". - With
FILTER_NULL_ON_FAILURE, unrecognized values returnnull, allowing you to reject invalid input.
Since PHP 8.0, FILTER_VALIDATE_BOOL is available as an alias for FILTER_VALIDATE_BOOLEAN.
Real-World Example: Reading an Environment Setting
<?php
$debugSetting = getenv('APP_DEBUG') ?: 'false';
$isDebug = filter_var($debugSetting, FILTER_VALIDATE_BOOLEAN);
if ($isDebug) {
ini_set('display_errors', '1');
}
Environment variables are always strings. Converting "false" with (bool) would turn debugging on — exposing error details on a live site. filter_var() interprets the text correctly.
Loose Comparison With Booleans
When a boolean is compared with == to a value of another type, PHP converts the other value to a boolean first.
<?php
var_dump(true == "false"); // "false" is a non-empty string → true
var_dump(false == "0"); // "0" is falsy → false == false
var_dump(false == []); // empty array is falsy
var_dump(true == 42); // non-zero number is truthy
Output
bool(true)
bool(true)
bool(true)
bool(true)
These results follow the conversion rules, but they rarely express what the programmer intended. Use strict comparison (===) when comparing with booleans:
<?php
var_dump(true === "false"); // bool(false)
Booleans and Databases
MySQL has no true boolean column type; BOOLEAN is an alias for TINYINT(1), storing 1 or 0. Depending on the database driver and its settings, PHP may receive these values as integers (1) or strings ("1").
<?php
$row = ['is_active' => '0']; // as it may arrive from the database
if ($row['is_active']) {
echo "Active";
} else {
echo "Inactive";
}
$isActive = (bool) (int) $row['is_active'];
var_dump($isActive);
Output
Inactive
bool(false)
"0" happens to be falsy, so the if works. But values such as "0.0" or " 0" from other sources would be truthy. Converting explicitly — first to int, then to bool — produces a reliable boolean regardless of how the value arrived.
Naming Boolean Variables and Functions
Boolean names should read naturally as yes/no questions:
| Prefix | Example |
|---|---|
is | $isActive, isValidEmail() |
has | $hasDiscount, hasPermission() |
can | $canEdit, canPublish() |
should | $shouldNotify |
Avoid negative names such as $isNotDisabled: if (!$isNotDisabled) forces the reader to resolve a double negative. Prefer $isEnabled.
Functions that answer a question should return a real bool and declare it:
<?php
function isWeekend(DateTimeInterface $date): bool
{
return $date->format('N') >= 6;
}
var_dump(isWeekend(new DateTime('2026-10-10')));
Output
bool(true)
format('N') returns the ISO day of the week (1 = Monday … 7 = Sunday); October 10, 2026, is a Saturday (6). The comparison already produces a boolean, so the function returns it directly — no if (...) { return true; } else { return false; } needed.
Common Mistakes
Checking Function Results Loosely
Problem: if (strpos($text, $word)).
Effect: A match at position 0 is treated as "not found".
Fix: Use !== false, or str_contains() / str_starts_with() in PHP 8.
Casting Text Like "false" With (bool)
Effect: "false", "no", and "off" become true.
Fix: Use filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE).
Echoing Booleans to Debug
Effect: false prints nothing; true prints 1.
Fix: Use var_dump() or var_export().
Expecting "0.0" or "00" to Be Falsy
Effect: Conditions run when they should not.
Fix: Convert to a number first ((float) $value) or validate the input.
Comparing Booleans With ==
Effect: true == "false" is true.
Fix: Use ===, or use the boolean directly in the condition.
Writing Redundant Conditionals
Problem:
if ($total > 1000) {
$isLarge = true;
} else {
$isLarge = false;
}
Fix: Assign the comparison directly: $isLarge = $total > 1000;
Best Practices
- Write
trueandfalsein lowercase. - Name boolean variables and functions as questions (
is,has,can). - Use booleans directly in conditions without comparing to
true. - Check functions that return
falseon failure with=== falseor!== false. - Convert text to booleans with
filter_var()andFILTER_VALIDATE_BOOLEAN. - Declare
boolreturn types for functions that answer yes/no questions. - Inspect booleans with
var_dump()orvar_export().
Official reference: https://www.php.net/manual/en/language.types.boolean.php