如何将字符串转换为布尔值?
$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。
当前回答
你应该能够使用(bool)强制转换为布尔型,但我不确定没有检查这是否适用于字符串“true”和“false”。
不过这可能值得一试
$myBool = (bool)"False";
if ($myBool) {
//do something
}
值得注意的是,当将以下内容放入其中时,将计算为布尔值False
if()
布尔值FALSE本身 整数0(零) 浮点数0.0(零) 空字符串和字符串"0" 零元素数组 一个没有成员变量的对象(仅适用于PHP 4) 特殊类型NULL(包括未设置的变量) 从空标记创建的SimpleXML对象
其他的都是真。
如下所述: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
其他回答
你应该能够使用(bool)强制转换为布尔型,但我不确定没有检查这是否适用于字符串“true”和“false”。
不过这可能值得一试
$myBool = (bool)"False";
if ($myBool) {
//do something
}
值得注意的是,当将以下内容放入其中时,将计算为布尔值False
if()
布尔值FALSE本身 整数0(零) 浮点数0.0(零) 空字符串和字符串"0" 零元素数组 一个没有成员变量的对象(仅适用于PHP 4) 特殊类型NULL(包括未设置的变量) 从空标记创建的SimpleXML对象
其他的都是真。
如下所述: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
其他的答案是过于复杂的事情。这是一个简单的逻辑问题。只要你的陈述正确就行了。
$boolString = 'false';
$result = 'true' === $boolString;
现在你的答案是两者之一
False,如果字符串是' False ', 或者true,如果你的字符串为true。
我必须注意filter_var($boolString, FILTER_VALIDATE_BOOLEAN);如果你需要像on/yes/1这样的字符串作为true的别名,仍然是一个更好的选择。
您可以使用json_decode来解码布尔值
$string = 'false';
$boolean = json_decode($string);
if($boolean) {
// Do something
} else {
//Do something else
}
我对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']);
使用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>";