Mark
Mark

Reputation: 69920

Parsing a string into a boolean value in PHP

Today I was playing with PHP, and I discovered that the string values "true" and "false" are not correctly parsed to boolean in a condition, for example considering the following function:

function isBoolean($value) {
   if ($value) {
      return true;
   } else {
      return false;
   }
}

If I execute:

isBoolean("true") // Returns true
isBoolean("") // Returns false
isBoolean("false") // Returns true, instead of false
isBoolean("asd") // Returns true, instead of false

It only seems to work with "1" and "0" values:

isBoolean("1") // Returns true
isBoolean("0") // Returns false

Is there a native function in PHP to parse "true" and "false" strings into boolean?

Upvotes: 149

Views: 100599

Answers (8)

Matt Janssen
Matt Janssen

Reputation: 1653

If your API only accepts the strings "true" or "false", with everything else becoming null, then try:

$boolean = ['true' => true, 'false' => false][$inputString] ?? null;

This assumes that $input is not an object. Null coalesce (??) was introduced in PHP 7.0.

Upvotes: 0

Eric Caron
Eric Caron

Reputation: 6273

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.

Upvotes: 475

Grey Perez
Grey Perez

Reputation: 20438

Easiest Way to safely convert to a boolean;

    $flag = 'true';

    if( filter_var( $flag,FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE ) !== null) {
      $flag = filter_var($flag,FILTER_VALIDATE_BOOLEAN);
    }

    gettype($flag); // Would Return 'Boolean'
    echo 'Val: '.$flag; // Would Output 'Val: 1'

Upvotes: 1

Matt Kantor
Matt Kantor

Reputation: 1754

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.

Upvotes: 4

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

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

Upvotes: 16

mario
mario

Reputation: 145482

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

Upvotes: 3

Pekka
Pekka

Reputation: 449395

Is there a function in PHP to parse "true" and "false" strings into boolean?

No - both are strings, and those both (as you say) evaluate to true. Only empty strings evaluate to false in PHP.

You would need to test for this manually. If at all possible, though, it would be better to work with "real" boolean values instead.

Upvotes: 1

BoltClock
BoltClock

Reputation: 723528

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

Upvotes: 6

Related Questions