PHP 判斷式 0 == 'string' 恆為 true - 2012

簡單的一個判斷式, 如下述:

<?php
$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 的解法

先講解法:

  1. 使用 === 來解決. (註: === 會比對 "型態 + 值" 是否相同, 詳見: PHP: Comparison Operators - Manual)
  2. 上面 === 是正解, 另外就是 盡量避免預設值 設為 0 或 False(雖然這樣子講怪怪的, 因為預設值設為 0 / False 是很習慣的事情. XD), 或者說, 設 0 或 False 的, 要特別注意.
  3. 註: 可以考慮 預設值設 -1
  4. 判斷式 盡量用 === 來判斷

範例 + 測試

<?php
$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), 官方文件有詳細說明.

下述摘錄自 官方文件說明: PHP: Strings - Manual - String conversion to numbers

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.

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

在〈PHP 判斷式 0 == 'string' 恆為 true - 2012〉中有 7 則留言

    1. 呵呵~ $a = true; $b = 200;
      不過
      < ?php $a = 100; $b = 200; if ($a && $b) { var_dump($a, $b); } ?>
      這樣子就會是正常的, 還是不要太偷懶的好~ 🙂

白目捷 發表迴響取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料