在PHP 7中我做了这个.输出应该是0对吗?但我得到1.为什么是这样?
<?php
echo "a"==0?1:0;
?>
Run Code Online (Sandbox Code Playgroud)
"a"== 0评估为true.
因为任何string is converted into an integer when compared with an integer.如果PHP无法正确转换字符串,则将其计算为0.因此0等于0,等于为真.
如果你想要答案为0,
你应该使用===而不是==,
因为普通运算符不比较类型.相反,它会尝试对项目进行类型转换.
同时===考虑项目的类型.
===表示"等于",
==表示"eeeeh ..有点看起来像"
另外,用于比较的PHP手册http://au.php.net/manual/en/language.operators.comparison.php
// double equal will cast the values as needed followin quite complex rules
0 == '0' // true, because PHP casted both sides to numbers
// triple equals returns true only when type and value match
0 === '0' // false
Run Code Online (Sandbox Code Playgroud)
仅供参考,来自PHP手册:
字符串转换为数字
在数值上下文中计算字符串时,结果值和类型将按如下方式确定.
如果字符串包含任何字符'.','e'或'E',则将其评估为float.否则,它将被评估为整数.
该值由字符串的初始部分给出.如果字符串以有效数字数据开头,则这将是使用的值.否则,该值将为0(零).有效数字数据是可选符号,后跟一个或多个数字(可选地包含小数点),后跟可选指数.指数是'e'或'E',后跟一个或多个数字.
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |