为什么(0 =='Hello')在PHP中返回true?

时间:2011-05-05 07:49:07

标签: php if-statement

嘿,如果您有以下代码,并想检查$key是否与我发现的Hello匹配,那么如果变量为{{{},则比较始终返回true 1}}。我遇到了一个特殊键的数组,并想知道为什么它没有按预期工作。 请参阅此代码以获取示例。

0

任何人都能解释一下吗?

5 个答案:

答案 0 :(得分:48)

运算符==!=不会比较类型。因此,PHP会自动将“Hello”转换为0intval('Hello'))的整数。如果不确定类型,请使用类型比较运算符===!==。或者更好地确定您在程序中的任何一点处理哪种类型。

答案 1 :(得分:3)

其他人已经很好地回答了这个问题。我只想提供一些其他的例子,你应该知道,所有这些都是由PHP的类型杂耍引起的。以下所有比较将返回 true

  • '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

答案 2 :(得分:1)

几乎任何非零值都会在幕后的php中转换为true。

所以1,2,3,4,'Hello','world'等都等于true,而0等于false

唯一的原因!==工作原因是因为它比较数据类型也是一样的

答案 3 :(得分:1)

因为PHP会进行自动转换以比较不同类型的值。您可以在PHP文档中看到table of type-conversion criteria

在您的情况下,字符串"Hello"会自动转换为数字,根据PHP,它是0。因此真正的价值。

如果要比较不同类型的值,则应使用类型安全运算符:

$value1 === $value2;

$value1 !== $value2;

通常,PHP会将每个无法识别为字符串的字符串计算为零。

答案 4 :(得分:0)

在php中,字符串“0”被转换为布尔值FALSE http://php.net/manual/en/language.types.boolean.php

相关问题