How to convert string to boolean php
Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP (taken from the documentation for empty
):
""
(an empty string);"0"
(0 as a string)
If you need to set a boolean based on the text value of a string, then you'll need to check for the presence or otherwise of that value.
$test_mode_mail = $string === 'true'? true: false;
EDIT: the above code is intended for clarity of understanding. In actual use the following code may be more appropriate:
$test_mode_mail = ($string === 'true');
or maybe use of the filter_var
function may cover more boolean values:
filter_var($string, FILTER_VALIDATE_BOOLEAN);
filter_var
covers a whole range of values, including the truthy values "true"
, "1"
, "yes"
and "on"
. See here for more details.
This method was posted by @lauthiamkok in the comments. I'm posting it here as an answer to call more attention to it.
Depending on your needs, you should consider using filter_var()
with the FILTER_VALIDATE_BOOLEAN
flag.
filter_var( true, FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'true', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 1, FILTER_VALIDATE_BOOLEAN); // true
filter_var( '1', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'on', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'yes', FILTER_VALIDATE_BOOLEAN); // true
filter_var( false, FILTER_VALIDATE_BOOLEAN); // false
filter_var( 'false', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 0, FILTER_VALIDATE_BOOLEAN); // false
filter_var( '0', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 'off', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 'no', FILTER_VALIDATE_BOOLEAN); // false
filter_var('asdfasdf', FILTER_VALIDATE_BOOLEAN); // false
filter_var( '', FILTER_VALIDATE_BOOLEAN); // false
filter_var( null, FILTER_VALIDATE_BOOLEAN); // false
The String "false"
is actually considered a "TRUE"
value by PHP.
The documentation says:
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
so if you do:
$bool = (boolean)"False";
or
$test = "false";
$bool = settype($test, 'boolean');
in both cases $bool
will be TRUE
. So you have to do it manually, like GordonM suggests.