PHP Booleans

La Lakshmi Priya Updated 29 Oct 2026
9 min read

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 >= 18 compares two numbers and produces true.
  • $cartTotal >= 500 produces false.
  • $role === "editor" || $role === "admin" combines two comparisons with the logical OR operator ||; the result is true if 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.

ValueTypeConverts To
falseboolfalse
0intfalse
0.0, -0.0floatfalse
"" (empty string)stringfalse
"0"stringfalse
[] (empty array)arrayfalse
nullnullfalse

(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.
  • -1 is 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

FunctionValid Result That Is FalsyFailure 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, true becomes "1" and false becomes an empty string. This is why echo false; prints nothing.
  • When converted to an integer, true is 1 and false is 0, so true + true equals 2.
  • json_encode() keeps booleans as JSON true / 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_BOOLEAN returns true for "1", "true", "on", and "yes" (case-insensitive), and false for "0", "false", "off", "no", and "".
  • Without FILTER_NULL_ON_FAILURE, unrecognized values such as "maybe" also return false, so you cannot distinguish "no" from "invalid input".
  • With FILTER_NULL_ON_FAILURE, unrecognized values return null, 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:

PrefixExample
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 true and false in lowercase.
  • Name boolean variables and functions as questions (is, has, can).
  • Use booleans directly in conditions without comparing to true.
  • Check functions that return false on failure with === false or !== false.
  • Convert text to booleans with filter_var() and FILTER_VALIDATE_BOOLEAN.
  • Declare bool return types for functions that answer yes/no questions.
  • Inspect booleans with var_dump() or var_export().

Official reference: https://www.php.net/manual/en/language.types.boolean.php

0 Comments

Reviewed before they appear

No comments yet.

Data Mining
Introduction to Data Mining Data Mining Implementation Process Data Mining Architecture Data Mining Techniques KDD: Knowledge Discovery in Databases History of Data Mining Data Mining Tools Data Mining vs Machine Learning Facebook Data Mining Social Media Data Mining Methods Clustering in Data Mining Text Data Mining Bagging vs Boosting Data Mining vs Data Warehousing Social Media Data Mining Data Mining: Bayesian Classifiers Data Mining: World Wide Web Different Types of Clustering Bitcoin Mining and Blockchain Data Mining Orange Data Mining Data Mining vs Big Data Decision Tree Induction Educational Data Mining Data Mining in Healthcare Apriori Algorithm Data Integration in Data Mining Difference Between Data Mining and Text Mining Discretization in Data Mining Redundancy and Correlation in Data Mining Classification of Data Mining Systems Classification Algorithms in Data Mining Data Generalization in Data Mining Classification and Prediction in Data Mining Regression in Data Mining What Is an Outlier in Data Mining Data Cleaning in Data Mining Data Processing in Data Mining Data Mining Task Primitives Web Content Mining, Web Structure Mining, and Web Usage Mini Binning in Data Mining KDD vs. Data Mining Noise in Data Mining BIRCH in Data Mining Stemming in Data Mining Feature Transformation in Data Mining Visual and Audio Data Mining Class Comparison Methods in Data Mining Data Selection in Data Mining Tasks and Functionalities of Data Mining Ubiquitous and Invisible Data Mining Importance of Data Mining Data Quality in Data Mining Mining Frequent Patterns in Data Mining Data Warehouse and OLAP Technology for Data Mining Need for Data Mining Pattern Evaluation Methods in Data Mining Logarithms and Exponents in Complexity Analysis Time Series Clustering What is the C4.5 Algorithm and How Does It Work? Expanding Contractions in Text Mining Cosine Similarity in Data Mining Lazy Learning in Data Mining Neural Networks in Data Mining Building a Text Normalizer Shallow Parsing Data Pipeline Orchestration Big Data vs Small Data Myths of Data Mining Data Reduction in Data Mining Data Mining Models Difference Between Data Mining and Data Science Difference Between Data Mining and Statistics Difference Between Data Mining and Web Mining Difference Between Data Mining and Data Analysis Difference Between Business Intelligence and Data Mining Difference Between Data Mining and Data Visualization Data Mining vs Data Analytics Types of Data Mining Difference Between Data Profiling and Data Mining Predictive Analytics vs Data Mining Difference Between Data Mining and OLAP Descriptive and Predictive Data Mining Difference Between Spatial and Temporal Data Mining Difference Between Classification and Clustering in Data Min Hierarchical Clustering in Data Mining Density-Based Clustering in Data Mining What Is Aggregation in Data Mining?
Ask about this post
AI Ask about this post

Ask questions about PHP Booleans and get answers drawn from it.

Signed-in readers only.