PHP Booleans

La Lakshmi Priya Updated 30 Oct 2026
9 min read ·Lesson 206 of 209

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.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PHP XML Parsers PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions
Ask about this post
AI Ask about this post

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

Signed-in readers only.