Parsing a string into a boolean value in PHP
There is a native PHP method of doing this which uses PHP's filter_var method:
$bool = filter_var($value, FILTER_VALIDATE_BOOLEAN);
According to PHP's manual:
Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.
If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.
In PHP only "0"
or the empty string coerce to false; every other non-empty string coerces to true. From the manual:
When converting to boolean, the following values are considered
FALSE
:
- the empty string, and the string "0"
You need to write your own function to handle the strings "true"
vs "false"
. Here, I assume everything else defaults to false:
function isBoolean($value) {
if ($value === "true") {
return true;
} else {
return false;
}
}
On a side note that could easily be condensed to
function isBoolean($value) {
return $value === "true";
}
The reason is that all strings evaluate to true
when converting them to boolean, except "0"
and ""
(empty string).
The following function will do exactly what you want: it behaves exactly like PHP, but will also evaluates the string "false"
as false
:
function isBoolean($value) {
if ($value && strtolower($value) !== "false") {
return true;
} else {
return false;
}
}
The documentation explains that: http://php.net/manual/en/language.types.boolean.php :
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
- the special type NULL (including unset variables)
- SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).