在 PHP 中将字符串解析为布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4775294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:19:53  来源:igfitidea点击:

Parsing a string into a boolean value in PHP

phpparsingboolean

提问by Mark

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:

今天我在玩 PHP,我发现字符串值 "true" 和 "false" 在条件中没有正确解析为布尔值,例如考虑以下函数:

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:

它似乎只适用于“1”和“0”值:

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

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

PHP 中是否有本机函数可以将“true”和“false”字符串解析为布尔值?

回答by Eric Caron

There is a native PHP method of doing this which uses PHP's filter_var method:

有一种使用 PHP 的 filter_var 方法执行此操作的原生 PHP 方法:

$bool = filter_var($value, FILTER_VALIDATE_BOOLEAN);

According to PHP's manual:

根据PHP 的手册

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.

为“1”、“true”、“on”和“yes”返回 TRUE。否则返回 FALSE。

如果设置了 FILTER_NULL_ON_FAILURE,则仅对“0”、“false”、“off”、“no”和“”返回 FALSE,对所有非布尔值返回 NULL。

回答by Arnaud Le Blanc

The reason is that all strings evaluate to truewhen converting them to boolean, except "0"and ""(empty string).

原因是所有字符串true在将它们转换为布尔值时评估为,除了"0"""(空字符串)。

The following function will do exactly what you want: it behaves exactly like PHP, but will also evaluates the string "false"as false:

以下函数将完全符合您的要求:它的行为与 PHP 完全一样,但也会将字符串计算"false"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:

文档解释说: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).

转换为布尔值时,以下值被视为 FALSE:

  • 布尔值 FALSE 本身
  • 整数 0(零)
  • 浮点数 0.0(零)
  • 空字符串和字符串“0”
  • 一个元素为零的数组
  • 特殊类型 NULL(包括未设置的变量)
  • 从空标签创建的 SimpleXML 对象

每隔一个值都被认为是 TRUE(包括任何资源)。

回答by BoltClock

In PHP only "0"or the empty string coerce to false; every other non-empty string coerces to true. From the manual:

仅在 PHP 中"0"或空字符串强制为 false;所有其他非空字符串强制为真。从手册

When converting to boolean, the following values are considered FALSE:

  • the empty string, and the string "0"

转换为布尔值时,会考虑以下值FALSE

  • 空字符串和字符串“0”

You need to write your own function to handle the strings "true"vs "false". Here, I assume everything else defaults to false:

您需要编写自己的函数来处理字符串"true"vs "false". 在这里,我假设其他所有内容都默认为 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";
}

回答by Matt Kantor

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 Countablethis will return (boolean) count($object)regardless of the value of (string) $object.

请注意,对于既可计数又可字符串转换的对象,这将有利于字符串值的计数来确定真实性。也就是说,如果$object instanceof Countable这将返回(boolean) count($object)无论价值(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 pastebinas well.

您可以在此处查看我使用的测试数据的行为以及其他几个函数的结果。从那个小 iframe 中浏览结果有点困难,因此您可以在整个页面中查看脚本输出,而不是(该 URL 没有记录,因此这可能不会永远有效)。万一这些链接有一天会消失,也会将代码放在 pastebin 上

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.

“应该是真的”和“不应该是真的”之间的界限非常随意;我使用的数据是根据我的需求和审美偏好分类的,你的可能会有所不同。

回答by mario

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

我正在使用此构造将字符串转换为布尔值,因为您需要true大多数其他值:

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

回答by Pekka

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

PHP 中是否有将“true”和“false”字符串解析为布尔值的函数?

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

不 - 两者都是字符串,而那些(如你所说)评估为true. false在 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.

您需要手动对此进行测试。不过,如果可能的话,最好使用“真实”布尔值来代替。

回答by Timothy Perez

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'

回答by Matt Janssen

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

如果您的 API 只接受字符串“true”或“false”,而其他所有内容都变为null,请尝试:

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

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

这假设它$input不是一个对象。空合并 ( ??) 是在 PHP 7.0 中引入的。