douzhen1234 2015-12-14 02:16
浏览 26

PHP:为什么这个比较评估为真? [重复]

The PHP 5.6 code:

$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";

This outputs:

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

I don't understand the last line of output. How can something true be compared to something false and have a comparison result of true?

Answer: The string and the integer are not both converted to booleans as I suspected. Instead, the string is converted to a number and then compared to 0. Because the string does not begin with a numeric character, it evaluates to the number 0 (var_dump((int)'hello') will output int 0). So the comparison returns true because "hello" == 0 becomes 0 == 0

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀
    • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
    • ¥15 关于#hadoop#的问题