Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a string into a boolean value in PHP

People also ask

Can you convert string to boolean?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

How parse boolean in PHP?

Use filter_var() function to convert string to boolean value. Approach using PHP filter_var() Function: The filter_var() function is used to filter a variable with specified filter. This function is used to both validate and sanitize the data.

How do you typecast a variable to boolean in PHP?

Casting Values to Boolean You can cast any variable to a boolean by prefixing it with (bool) or (boolean) . However, this isn't always necessary because PHP can determine from the context if you want a value to be evaluated as a boolean. The boolean false itself naturally evaluates to false .

How check if value is boolean in PHP?

The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.


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.


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).


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";
}

I recently needed a "loose" boolean conversion function to handle strings like the ones you're asking about (among other things). I found a few different approaches and came up with a big set of test data to run through them. Nothing quite fit my needs so I wrote my own:

function loosely_cast_to_boolean($value) {
    if(is_array($value) || $value instanceof Countable) {
        return (boolean) count($value);
    } else if(is_string($value) || is_object($value) && method_exists($value, '__toString')) {
        $value = (string) $value;
        // see http://www.php.net/manual/en/filter.filters.validate.php#108218
        // see https://bugs.php.net/bug.php?id=49510
        $filtered = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
        if(!is_null($filtered)) {
            return $filtered;
        } else {
            // "none" gets special treatment to be consistent with ini file behavior.
            // see documentation in php.ini for more information, in part it says: 
            // "An empty string can be denoted by simply not writing anything after 
            // the equal sign, or by using the None keyword".
            if(strtolower($value) === 'none') {
                $value = '';
            }
            return (boolean) $value;
        }
    } else {
        return (boolean) $value;
    }
}

Note that for objects which are both countable and string-castable, this will favor the count over the string value to determine truthiness. That is, if $object instanceof Countable this will return (boolean) count($object) regardless of the value of (string) $object.

You can see the behavior for the test data I used as well as the results for several other functions here. It's kind of hard to skim the results from that little iframe, so you can view the script output in a full page, instead (that URL is undocumented so this might not work forever). In case those links die some day, I put the code up on pastebin as well.

The line between what "ought to be true" and what oughtn't is pretty arbitrary; the data I used is categorized based on my needs and aesthetic preferences, yours may differ.


I'm using this construct to morph strings into booleans, since you want true for most other values:

$str = "true";
$bool = !in_array($str, array("false", "", "0", "no", "off"));