Question
How can a string such as 'false' be converted to a Boolean value in PHP?
$string = 'false';
$test_mode_mail = settype($string, 'boolean');
var_dump($test_mode_mail);
if ($test_mode_mail) {
echo 'Test mode is on.';
}
This code outputs bool(true), but the expected Boolean value for the string 'false' is bool(false). Why does this happen, and what is the correct way to convert the string?
Short Answer
You will learn the difference between converting a value and receiving a function's success result in PHP. You will also learn PHP's string-to-Boolean casting rules and how to reliably parse text values such as 'true' and 'false'.
Concept
settype() changes the type of the variable passed to it by reference. Its return value does not contain the converted variable. Instead, it returns true when the conversion operation succeeds.
$string = 'false';
$result = settype($string, 'boolean');
var_dump($result); // bool(true): settype succeeded
var_dump($string); // bool(true): converted value
There is a second important detail: PHP's normal Boolean conversion does not interpret the word 'false' as false. When converting a string to bool, PHP considers only these values false:
- the empty string:
'' - the string
'0'
Every other non-empty string is true, including 'false', 'no', 'off', and 'hello'.
This matters when handling form fields, environment variables, query parameters, JSON-like text, or configuration files. Those sources often represent Booleans as text, so they must be according to the format's rules rather than simply cast.
Mental Model
Think of settype() as a mechanic changing the contents of a labelled box.
- The variable
$stringis the box. settype($string, 'boolean')changes what is inside the box.- The function's return value is the mechanic saying, “The conversion was completed successfully.”
That success message is true; it is not the converted value.
Separately, a PHP Boolean cast asks a simple question about strings: “Is this string non-empty and not exactly '0'?” It does not read the English meaning of words such as 'false'. Use filter_var() when you need PHP to recognize common Boolean words.
Syntax and Examples
Use filter_var() with FILTER_VALIDATE_BOOLEAN to parse common text representations of Booleans.
$value = 'false';
$testMode = filter_var($value, FILTER_VALIDATE_BOOLEAN);
var_dump($testMode); // bool(false)
FILTER_VALIDATE_BOOLEAN recognizes these values case-insensitively:
Parsed as true | Parsed as false |
|---|---|
'1' | '0' |
'true' | 'false' |
'on' |
Step by Step Execution
Consider this code:
$input = 'false';
$isTestMode = filter_var($input, FILTER_VALIDATE_BOOLEAN);
if ($isTestMode) {
echo 'Test mode is on.';
} else {
echo 'Test mode is off.';
}
Execution trace:
$inputstores the string'false'.filter_var()applies the Boolean validation filter.- The filter recognizes
'false'as a false representation and returns the Booleanfalse. $isTestModenow containsfalse.- The
ifcondition is false, so theelsebranch runs. - The output is
Test mode is off.
Compare that with a cast:
$isTestMode = () ;
Real World Use Cases
- Environment variables: Deployment settings such as
APP_DEBUG=falseare delivered as strings. Parse them before enabling debugging. - HTML forms: A checkbox or select menu may submit
'on','off','yes', or'no'. - API query parameters: An endpoint such as
/users?includeInactive=falsereceives text, not a native Boolean. - Configuration files: INI-style or custom configuration values may need conversion before application logic uses them.
- CSV imports: Spreadsheets often contain values like
TRUE,FALSE,Yes, andNothat need predictable validation.
In each case, use FILTER_NULL_ON_FAILURE if invalid input should produce an error instead of silently becoming false.
Real Codebase Usage
In production code, parse external input at the boundary of your application. Once validated, pass real bool values through the rest of the codebase.
Validate an optional query parameter
$rawValue = $_GET['include_inactive'] ?? 'false';
$includeInactive = filter_var(
$rawValue,
FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE
);
if ($includeInactive === null) {
http_response_code(400);
exit('include_inactive must be true or false.');
}
// $includeInactive is now definitely bool(true) or bool(false).
Use a guard clause for required configuration
$debug = filter_var(
getenv('APP_DEBUG'),
FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE
);
if ($debug === null) {
throw new RuntimeException('APP_DEBUG must be a valid Boolean value.');
}
The strict comparison === null is important. A valid parsed value of must not be treated as an error.
Common Mistakes
Assigning settype() to another variable
$value = 'false';
$isEnabled = settype($value, 'boolean');
var_dump($isEnabled); // bool(true)
$isEnabled receives the success status of settype(). The changed value is $value.
$value = 'false';
settype($value, 'boolean');
var_dump($value); // bool(true), due to PHP casting rules
Expecting (bool) 'false' to be false
$isEnabled = (bool) 'false'; // true
PHP does not interpret the word. Use filter_var() for text Boolean values.
Comparisons
| Approach | What it does | Result for 'false' | Best use |
|---|---|---|---|
(bool) $value | Uses PHP's native type-juggling rules | true | When native PHP casting is intended |
settype($value, 'boolean') | Mutates $value; returns conversion success | $value becomes true | Rarely needed; casts are usually clearer |
filter_var($value, FILTER_VALIDATE_BOOLEAN) | Parses common textual Boolean values | false | Form, configuration, and request input |
Cheat Sheet
// Parse text Boolean values
$enabled = filter_var('true', FILTER_VALIDATE_BOOLEAN); // true
$enabled = filter_var('false', FILTER_VALIDATE_BOOLEAN); // false
// Detect invalid input
$enabled = filter_var(
'unknown',
FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE
); // null
// Check parsing result safely
if ($enabled === null) {
// Invalid input
}
// PHP native casts: only '' and '0' are false strings
(bool) ''; // false
(bool) '0'; // false
(bool) 'false'; // true
(bool) 'no'; // true
// settype mutates its first argument and returns success
$value = '0';
$success = settype($value, 'boolean');
// $success is true; $value is false
Rules to remember:
FAQ
Why does settype() return true in PHP?
It returns whether the type conversion succeeded. The converted value is stored back in the first argument.
Why is (bool) 'false' true in PHP?
Because 'false' is a non-empty string and is not exactly '0'. PHP's standard cast does not parse the word's meaning.
What is the best way to convert 'true' and 'false' strings in PHP?
Use filter_var($value, FILTER_VALIDATE_BOOLEAN). Add FILTER_NULL_ON_FAILURE when invalid values should be rejected.
Does FILTER_VALIDATE_BOOLEAN support uppercase values?
Yes. It recognizes supported text values case-insensitively, such as 'TRUE' and 'False'.
How can I distinguish false from invalid input?
Use FILTER_NULL_ON_FAILURE, then check === null. false is a valid parsed value; indicates failure.
Mini Project
Description
Build a small configuration parser for a test_mode setting. Configuration and environment values commonly arrive as strings, but application code needs a reliable Boolean before deciding whether to enable a feature.
Goal
Parse a text setting as true or false, reject invalid values, and display the resulting application mode.
Requirements
Use a string variable named $rawTestMode as the configuration input.
Parse the input with FILTER_VALIDATE_BOOLEAN and FILTER_NULL_ON_FAILURE.
Display an error message for invalid input.
Display whether test mode is enabled or disabled for valid input.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.