簡體   English   中英

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

[英]Why does (0 == 'Hello') return true in PHP?

嘿,如果您有以下代碼並想檢查$key是否匹配Hello我發現,如果變量為0 ,比較總是返回true 當一個特殊鍵的數組時,我遇到了這個問題,並想知道為什么它沒有按預期工作。 有關示例,請參見此代碼。

$key = 1;
if ($key != 'Hello') echo 'Hello'; //echoes hello

$key = 2;
if ($key != 'Hello') echo 'Hello'; //echoes hello

$key = 0;
if ($key != 'Hello') echo '0Hello'; //doesnt echo hello. why?
if ($key !== 'Hello') echo 'Hello'; //echoes hello

誰能解釋一下?

運算符==!=不比較類型。 因此 PHP 自動將 'Hello' 轉換為 integer ,即0 ( intval('Hello') )。 如果不確定類型,請使用類型比較運算符===!== 或者更好地確定您在程序中的任何時候處理的類型。

其他人已經很好地回答了這個問題。 我只是想舉一些其他的例子,你應該知道,都是由PHP的類型雜耍引起的。 以下所有比較都將返回true

  • 'abc' == 0
  • 0 == null
  • '' == null
  • 1 == '1y?z'

因為我發現這種行為很危險,所以我編寫了自己的 equal 方法並在我的項目中使用它:

/**
 * 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;
}

希望這可以幫助某人使他的應用程序更可靠,原始文章可以在這里找到:等於或不等於

在幕后的 php 中,幾乎所有非零值都會轉換為 true。

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

!== 起作用的唯一原因是因為它比較的數據類型也相同

因為 PHP 會自動轉換來比較不同類型的值。 您可以在 PHP 文檔中查看類型轉換標准表

在您的情況下,字符串"Hello"會自動轉換為數字,根據 PHP,該數字為0 因此,真正的價值。

如果你想比較不同類型的值,你應該使用類型安全的操作符:

$value1 === $value2;

或者

$value1 !== $value2;

通常,PHP 將每個無法識別為數字的字符串計算為零。

In php, the string "0" is converted to the boolean FALSE http://php.net/manual/en/language.types.boolean.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM