如何将字符串转换为布尔值?
$string = 'false';
$test_mode_mail = settype($string, 'boolean');
var_dump($test_mode_mail);
if($test_mode_mail) echo 'test mode is on.';
它返回,
布尔真
但它应该是布尔值为false。
如何将字符串转换为布尔值?
$string = 'false';
$test_mode_mail = settype($string, 'boolean');
var_dump($test_mode_mail);
if($test_mode_mail) echo 'test mode is on.';
它返回,
布尔真
但它应该是布尔值为false。
当前回答
一种简单的方法是检查您认为为真值的数组。
$wannabebool = "false";
$isTrue = ["true",1,"yes","ok","wahr"];
$bool = in_array(strtolower($wannabebool),$isTrue);
其他回答
使用preg_match()编辑显示工作解决方案;根据包含true的字符串返回布尔值true或false。与其他答案相比,这可能比较重,但可以很容易地调整以适合布尔值需要的任何字符串。
$test_mode_mail = 'false';
$test_mode_mail = 'true';
$test_mode_mail = 'true is not just a perception.';
$test_mode_mail = gettype($test_mode_mail) !== 'boolean' ? (preg_match("/true/i", $test_mode_mail) === 1 ? true:false):$test_mode_mail;
echo ($test_mode_mail === true ? 'true':'false')." ".gettype($test_mode_mail)." ".$test_mode_mail."<br>";
我对wordpress shortcode属性感到困惑,我决定写一个自定义函数来处理所有可能性。也许对某些人有用:
function stringToBool($str){
if($str === 'true' || $str === 'TRUE' || $str === 'True' || $str === 'on' || $str === 'On' || $str === 'ON'){
$str = true;
}else{
$str = false;
}
return $str;
}
stringToBool($atts['onOrNot']);
当使用JSON时,我必须通过$_POST发送一个布尔值。当我做类似的事情时,我也遇到了类似的问题:
if ( $_POST['myVar'] == true) {
// do stuff;
}
在上面的代码中,我的布尔值被转换为JSON字符串。
为了克服这个问题,你可以使用json_decode()解码字符串:
//assume that : $_POST['myVar'] = 'true';
if( json_decode('true') == true ) { //do your stuff; }
(这通常适用于布尔值转换为字符串并通过其他方式发送到服务器,即,除了使用JSON。)
字符串总是计算为布尔值true,除非它们有一个被PHP认为是“空”的值(取自文档中的empty):
""(空字符串); "0"(0作为字符串)
如果需要根据字符串的文本值设置布尔值,则需要检查该值是否存在。
$test_mode_mail = $string === 'true'? true: false;
编辑:上面的代码是为了清晰地理解。在实际使用中,下面的代码可能更合适:
$test_mode_mail = ($string === 'true');
或者使用filter_var函数可以覆盖更多的布尔值:
filter_var($string, FILTER_VALIDATE_BOOLEAN);
Filter_var涵盖了整个范围的值,包括真值“true”,“1”,“yes”和“on”。请看这里了解更多细节。
字符串“false”实际上被PHP视为“TRUE”值。 文件说:
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";
or
$test = "false";
$bool = settype($test, 'boolean');
在这两种情况下,$bool将为TRUE。所以你必须手动操作,就像GordonM建议的那样。