Parsing a string into a boolean value in PHP

2019-01-16 03:49发布

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?

7条回答
Emotional °昔
2楼-- · 2019-01-16 04:23

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'
查看更多
趁早两清
3楼-- · 2019-01-16 04:30

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.

查看更多
对你真心纯属浪费
4楼-- · 2019-01-16 04:31

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.

查看更多
Melony?
5楼-- · 2019-01-16 04:31

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"));
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-16 04:38

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";
}
查看更多
放我归山
7楼-- · 2019-01-16 04:39

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.

查看更多
登录 后发表回答