其他人已经很好地回答了这个问题。我只想给出一些其他的例子,你应该知道,所有这些都是由PHP的类型杂耍造成的。以下所有的比较将返回真正:
- 'ABC' == 0
- 0 == NULL
- '' == NULL
- 1 ==“1Y?Z”
,因为我发现这种行为的危险,我写我自己平等的方法,在我的项目中使用它:
/**
* Checks if two values are equal. In contrast to the == operator,
* the values are considered different, if:
* - one value is null and the other not, or
* - one value is an empty string and the other not
* This helps avoid strange behavier with PHP's type juggling,
* all these expressions would return true:
* 'abc' == 0; 0 == null; '' == null; 1 == '1y?z';
* @param mixed $value1
* @param mixed $value2
* @return boolean True if values are equal, otherwise false.
*/
function sto_equals($value1, $value2)
{
// identical in value and type
if ($value1 === $value2)
$result = true;
// one is null, the other not
else if (is_null($value1) || is_null($value2))
$result = false;
// one is an empty string, the other not
else if (($value1 === '') || ($value2 === ''))
$result = false;
// identical in value and different in type
else
{
$result = ($value1 == $value2);
// test for wrong implicit string conversion, when comparing a
// string with a numeric type. only accept valid numeric strings.
if ($result)
{
$isNumericType1 = is_int($value1) || is_float($value1);
$isNumericType2 = is_int($value2) || is_float($value2);
$isStringType1 = is_string($value1);
$isStringType2 = is_string($value2);
if ($isNumericType1 && $isStringType2)
$result = is_numeric($value2);
else if ($isNumericType2 && $isStringType1)
$result = is_numeric($value1);
}
}
return $result;
}
希望这有助于有人做了他的申请更加坚实,原创文章可在这里找到: Equal or not equal
有趣的是,有多少人没有正确阅读或理解问题。 – 2011-05-05 08:14:19