關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • PHP 字串比較問題

    Posted on October 2nd, 2006 Sam Tang No comments

    在 PHP 做字串比較時,以下情況會發生問題:

    CODE:
    1. <?php
    2. var_dump('01' == '1.');
    3. ?>

    以上的 '01' 及 '1.' 是不同,理應回傳 false,但實際執行時卻會回傳 true。原因是 PHP 會自動將兩個字串轉換為數值,而 '01' 及 '1.' 同樣會轉換成 1,所以回傳會是 true。

    解決方法是是用 "===" 取代 "==",因此程式碼應改成:

    CODE:
    1. <?php
    2. var_dump('01' === '1.');
    3. ?>


    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word