PHP:为什么这个比较评估为真?

时间:2015-12-14 02:16:22

标签: php boolean-logic

PHP 5.6代码:

$nl = '<br/>';
$text = 'hello';
$res = $text? 'true': 'false';
echo "$text evaluates to $res $nl";

$num = 0;
$res = $num? 'true': 'false';
echo "0 evaluates to $res $nl";

$res = $text == 0? 'true': 'false';
echo "$text == $num evaluates to $res $nl";

输出:

hello evaluates to true
0 evaluates to false
hello == 0 evaluates to true

我不理解输出的最后一行。如何将true与某些内容false进行比较并得到true的比较结果?

答案:我怀疑字符串和整数都转换为布尔值。相反,字符串将转换为数字,然后与0进行比较。因为字符串不是以数字字符开头,所以它的计算结果为0(var_dump((int)'hello')将输出int 0)。因此,比较会返回true,因为"hello" == 0变为0 == 0

0 个答案:

没有答案