如何将字符串转换为布尔值 php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7336861/
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
How to convert string to boolean php
提问by laukok
How can I convert string to boolean
?
如何将字符串转换为boolean
?
$string = 'false';
$test_mode_mail = settype($string, 'boolean');
var_dump($test_mode_mail);
if($test_mode_mail) echo 'test mode is on.';
it returns,
它返回,
boolean true
布尔真
but it should be boolean false
.
但应该是boolean false
。
回答by Brad
This method was posted by @lauthiamkok in the comments. I'm posting it here as an answer to call more attention to it.
此方法由@lauthiamkok 在评论中发布。我将它张贴在这里作为一个答案,以引起更多的关注。
Depending on your needs, you should consider using filter_var()
with the FILTER_VALIDATE_BOOLEAN
flag.
根据您的需要,您应该考虑filter_var()
与FILTER_VALIDATE_BOOLEAN
标志一起使用。
filter_var( 'true', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 1, FILTER_VALIDATE_BOOLEAN); // true
filter_var( '1', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'on', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'yes', FILTER_VALIDATE_BOOLEAN); // true
filter_var( 'false', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 0, FILTER_VALIDATE_BOOLEAN); // false
filter_var( '0', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 'off', FILTER_VALIDATE_BOOLEAN); // false
filter_var( 'no', FILTER_VALIDATE_BOOLEAN); // false
filter_var('asdfasdf', FILTER_VALIDATE_BOOLEAN); // false
filter_var( '', FILTER_VALIDATE_BOOLEAN); // false
filter_var( null, FILTER_VALIDATE_BOOLEAN); // false
回答by GordonM
Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP (taken from the documentation for empty
):
字符串总是计算为布尔值 true ,除非它们的值被 PHP 视为“空”(取自 的文档empty
):
""
(an empty string);"0"
(0 as a string)
""
(空字符串);"0"
(0 作为字符串)
If you need to set a boolean based on the text value of a string, then you'll need to check for the presence or otherwise of that value.
如果需要根据字符串的文本值设置布尔值,则需要检查该值是否存在。
$test_mode_mail = $string === 'true'? true: false;
EDIT: the above code is intended for clarity of understanding. In actual use the following code may be more appropriate:
编辑:上面的代码是为了清楚地理解。在实际使用中,下面的代码可能更合适:
$test_mode_mail = ($string === 'true');
or maybe use of the filter_var
function may cover more boolean values:
或者该filter_var
函数的使用可能涵盖更多布尔值:
filter_var($string, FILTER_VALIDATE_BOOLEAN);
filter_var
covers a whole range of values, including the truthy values "true"
, "1"
, "yes"
and "on"
. See herefor more details.
filter_var
覆盖整个范围的值,包括truthy值"true"
,"1"
,"yes"
和"on"
。请参阅此处了解更多详情。
回答by wosis
The String "false"
is actually considered a "TRUE"
value by PHP.
The documentation says:
字符串"false"
实际上"TRUE"
被 PHP视为一个值。文档说:
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
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
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
要将值显式转换为布尔值,请使用 (bool) 或 (boolean) 强制转换。但是,在大多数情况下,强制转换是不必要的,因为如果运算符、函数或控制结构需要布尔参数,则会自动转换值。
另请参阅类型杂耍。
转换为布尔值时,以下值被视为 FALSE:
布尔值 FALSE 本身
整数 0(零)
浮点数 0.0(零)
空字符串和字符串“0”
一个元素为零的数组
具有零成员变量的对象(仅限 PHP 4)
特殊类型 NULL(包括未设置的变量)
从空标签创建的 SimpleXML 对象
每隔一个值都被认为是 TRUE(包括任何资源)。
so if you do:
所以如果你这样做:
$bool = (boolean)"False";
or
或者
$test = "false";
$bool = settype($test, 'boolean');
in both cases $bool
will be TRUE
. So you have to do it manually, like GordonM suggests.
在这两种情况下$bool
都会TRUE
。所以你必须手动完成,就像 GordonM 建议的那样。
回答by Nishanth Shaan
When working with JSON, I had to send a Boolean value via $_POST
. I had a similar problem when I did something like:
使用 JSON 时,我必须通过$_POST
. 当我执行以下操作时,我遇到了类似的问题:
if ( $_POST['myVar'] == true) {
// do stuff;
}
In the code above, my Boolean was converted into a JSON string.
在上面的代码中,我的布尔值被转换为 JSON 字符串。
To overcome this, you can decode the string using json_decode()
:
为了克服这个问题,您可以使用json_decode()
以下方法解码字符串:
//assume that : $_POST['myVar'] = 'true';
if( json_decode('true') == true ) { //do your stuff; }
(This should normally work with Boolean values converted to string and sent to the server also by other means, i.e., other than using JSON.)
(这通常适用于将布尔值转换为字符串并通过其他方式发送到服务器,即使用 JSON 以外的方式。)
回答by souparno majumder
you can use json_decode to decode that boolean
你可以使用 json_decode 来解码那个布尔值
$string = 'false';
$boolean = json_decode($string);
if($boolean) {
// Do something
} else {
//Do something else
}
回答by mrded
(boolean)json_decode(strtolower($string))
It handles all possible variants of $string
它处理所有可能的变体 $string
'true' => true
'True' => true
'1' => true
'false' => false
'False' => false
'0' => false
'foo' => false
'' => false
回答by SandroMarques
If your "boolean" variable comes from a global array such as $_POST and $_GET, you can use filter_input()
filter function.
如果你的“boolean”变量来自一个全局数组,比如 $_POST 和 $_GET,你可以使用filter_input()
filter 函数。
Example for POST:
POST 示例:
$isSleeping = filter_input(INPUT_POST, 'is_sleeping', FILTER_VALIDATE_BOOLEAN);
If your "boolean" variable comes from other source you can use filter_var()
filter function.
如果您的“boolean”变量来自其他来源,您可以使用filter_var()
过滤功能。
Example:
例子:
filter_var('true', FILTER_VALIDATE_BOOLEAN); // true
回答by anayarojo
You can use boolval($strValue)
您可以使用 boolval($strValue)
Examples:
例子:
<?php
echo '0: '.(boolval(0) ? 'true' : 'false')."\n";
echo '42: '.(boolval(42) ? 'true' : 'false')."\n";
echo '0.0: '.(boolval(0.0) ? 'true' : 'false')."\n";
echo '4.2: '.(boolval(4.2) ? 'true' : 'false')."\n";
echo '"": '.(boolval("") ? 'true' : 'false')."\n";
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n";
echo '"0": '.(boolval("0") ? 'true' : 'false')."\n";
echo '"1": '.(boolval("1") ? 'true' : 'false')."\n";
echo '[1, 2]: '.(boolval([1, 2]) ? 'true' : 'false')."\n";
echo '[]: '.(boolval([]) ? 'true' : 'false')."\n";
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n";
?>
Documentation http://php.net/manual/es/function.boolval.php
回答by Brandon Sanders
the easiest thing to do is this:
最简单的方法是:
$str = 'TRUE';
$boolean = strtolower($str) == 'true' ? true : false;
var_dump($boolean);
Doing it this way, you can loop through a series of 'true', 'TRUE', 'false' or 'FALSE' and get the string value to a boolean.
这样做,您可以遍历一系列“真”、“真”、“假”或“假”,并将字符串值设为布尔值。
回答by Dmitry
function stringToBool($string){
return ( mb_strtoupper( trim( $string)) === mb_strtoupper ("true")) ? TRUE : FALSE;
}
or
或者
function stringToBool($string) {
return filter_var($string, FILTER_VALIDATE_BOOLEAN);
}