简单的一个判断式, 如下述:
$types = 0;
if ($types == 'abc')
echo 'a';
else
echo 'b';
?>
答案是印出 a (预期应该要印出 b, 结果却印出 a)
注1: 这种情况平常比较容易出现在会给默认值的地方, ex: function abc($input, $types = 0) {...}
注2: 目前确定 PHP 5.3, 5.4 都是这样子的状况, 看官方说明这个并不算是 Bug, 应该会一直持续下去.
PHP 判断式 0 == 'string' 恒为 true 的解法
先讲解法:
使用 === 来解决. (注: === 会比对 "型态 + 值" 是否相同, 详见: PHP: Comparison Operators - Manual)
上面 === 是正解, 另外就是 尽量避免默认值 设为 0 或 False(虽然这样子讲怪怪的, 因为默认值设为 0 / False 是很习惯的事情. XD), 或者说, 设 0 或 False 的, 要特别注意.
注: 可以考虑 默认值设 -1
判断式 尽量用 === 来判断
范例 + 测试
$a = 0;
echo ($a === 'abc') ? "0 === abc\n" : "0 !== abc\n";
$a = 0;
echo ($a == 'abc') ? "0 = abc\n" : "0 != abc\n";
$a = 1;
echo ($a == 'abc') ? "1 = abc\n" : "1 != abc\n";
$a = false;
echo ($a == 'abc') ? "false = abc\n" : "false != abc\n";
$a = true;
echo ($a == 'abc') ? "true = abc\n" : "true != abc\n";
$a = '0';
echo ($a == 'abc') ? "'0' = abc\n" : "'0' != abc\n";
$a = 'a';
echo ($a == 'abc') ? "a = abc\n" : "a != abc\n";
?>
运行结果
0 !== abc
0 = abc
1 != abc
false != abc
true = abc
'0' != abc
a != abc
PHP 判断式 0 == 'string' 恒为 true 问题追踪 与 说明
这个问题在 2006年(PHP 5.2版)就已经有被人提到了, 但是都不被列为 Bug + Wont fix (下述为 Bug list), 官方文档有详细说明.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
简单说 0 == "string" 会恒为 true 的原因就是:, 因为字符串转换成 integer 会变成 0 (使用 strtod() 来作 ATOI 的时候, 无法转换 就会变成 0), 所以用 === 解决.
详细可见: "man 3 strtod" - strtod, strtof, strtold - convert ASCII string to floating-point number
相关网页
php string comparasion to 0 integer returns true?
Use comparison operator with type check "===". Look here for the example http://php.net/manual/en/language.operators.comparison.php and explanation why not-numerical string compared to zero always returns true.