如何将字符串转换为布尔值?

$string = 'false';

$test_mode_mail = settype($string, 'boolean');

var_dump($test_mode_mail);

if($test_mode_mail) echo 'test mode is on.';

它返回,

布尔真

但它应该是布尔值为false。


当前回答

使用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>"; 

其他回答

其他的答案是过于复杂的事情。这是一个简单的逻辑问题。只要你的陈述正确就行了。

$boolString = 'false';
$result = 'true' === $boolString;

现在你的答案是两者之一

False,如果字符串是' False ', 或者true,如果你的字符串为true。

我必须注意filter_var($boolString, FILTER_VALIDATE_BOOLEAN);如果你需要像on/yes/1这样的字符串作为true的别名,仍然是一个更好的选择。

@GordonM的回答很好。 但如果$string已经为真(即,字符串不是字符串而是布尔true),它将失败…这似乎不合逻辑。

延伸一下他的回答,我会用:

$test_mode_mail = ($string === 'true' OR $string === true));

字符串“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建议的那样。

最简单的方法是:

$str = 'TRUE';

$boolean = strtolower($str) == 'true' ? true : false;

var_dump($boolean);

这样做,你可以循环一系列'true', 'true', 'false'或'false',并将字符串值获取为布尔值。

filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

$string = 1; // true
$string ='1'; // true
$string = 'true'; // true
$string = 'trUe'; // true
$string = 'TRUE'; // true
$string = 0; // false
$string = '0'; // false
$string = 'false'; // false
$string = 'False'; // false
$string = 'FALSE'; // false
$string = 'sgffgfdg'; // null

您必须指定FILTER_NULL_ON_FAILURE,否则即使$string包含其他内容,您也将始终得到false。