簡體   English   中英

布爾值和字符串條件

[英]Boolean and string condition

我必須將我的狀態更改為方法中的單詞,但是當我將參數作為字符串傳遞給方法時,我從以下兩個條件得到結果:

public static function Status($status)
{
    if ($status == true || $status == True  || $status == 'true' || $status == 'True' || $status == 1)
    {
        echo "true";
    }
   if ($status == false || $status == False || $status == 'false' || $status == 'False' || $status == 0)
    {
        echo "false";
    }
}

當我將'False'值作為字符串傳遞給方法時,我得到truefalse結果,但我對字符串值沒有任何問題。

您應該使用===而不是==來檢查值是否相同。 因為如果比較沒有檢查變量類型,任何字符串都將被視為true 所以,將代碼更改為

function Status($status)
{
    if ($status === true || $status === True  || $status === 'true' || $status === 'True' || $status === 1)
    {
        echo "true";
    }
    if ($status === false || $status === False || $status === 'false' || $status === 'False' || $status === 0)
    {
        echo "false";
    }
}

http://php.net/manual/en/language.operators.comparison.php

一個可能派上用場的簡單技巧:

if (is_string($status)) $status = json_decode($status);
if ($status) {
   echo "true";
}
else {
   echo "false";
} 

json_decode將'False'或'false'轉換為布爾值false ,與true相同。

另一種方法是單獨留下字符串,因此將布爾值和整數轉換為字符串'true'和'false'。

if (!is_string($status)) $status = ($status) ? "true" : "false";
echo $status;

暫無
暫無

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

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