How can I parse a string into a boolean value in PHP?

Solution

By default, in PHP all strings are evaluated as true when converted to boolean, except for “0” and “” (the empty string).

If you also want the string “false” to be treated as false, you can use the following function:


function isBoolean($value) {
    if ($value && strtolower($value) !== "false") {
        return true;
    } else {
        return false;
    }
}

This mimics PHP’s built-in behavior, with the added rule that “false” is considered false.

According to the PHP documentation on booleans, the following values evaluate to false when cast to boolean:

false (the boolean itself)

0 (integer zero)

0.0 (float zero)

“” (empty string) and “0” (string zero)

An array with zero elements

NULL (including unset variables)

SimpleXML objects created from empty tags

Every other value evaluates to true (including any non-empty string and any resource).