2014-01-20 45 views
-1

我有這樣的代碼:如果條件和空變量

If(!isset($a) || empty($a)) 
{ 
    // code to run when $a not set or empty; 
} 
Elseif ($a==0) 
{ 
    //code to run when $a is equal 0 
} 
Else 
{ 
     //code to run in all other scenarios 
} 

的問題是,當$ a等於0,則空($ a)是真實和第一代碼運行。我需要第二個跑步。我該怎麼做?

+0

那麼,到底是什麼*爲*的條件?你想要測試什麼? – deceze

+0

我想查看是否設置了$ a,如果是,則運行第一個代碼。如果它是空的(這意味着空字符串或設置爲空)運行第一個代碼。如果它等於0,則運行第二個代碼,如果是其他任何內容(負數或正數),則運行第三個代碼。不明白爲什麼它是不可理解的。 – user2395238

回答

0

試試這個:

if((!isset($a) || empty($a)) && $a !== 0) 
{ 
    // code runs when $a not set or empty and $a is not 0; 
} 
elseif ($a === 0) 
{ 
    //code runs when $a is equal 0 
} 
else 
{ 
     //code runs in all other scenarios 
} 

更新: 改爲類型安全的比較。

+0

這也沒有工作。如果我設置$ a =「」第二個代碼運行,即使我想要它第一個運行。它看起來像在PHP $ a =「」和$ a = 0是一樣的。 – user2395238

+0

我找到了解決方案,您的答案是最接近的,並激勵我嘗試我嘗試的方法。如果你修改你的(添加等號)來匹配我的我會接受你的回答 – user2395238

+0

沒錯 - 在這種情況下最好使用類型安全比較。感謝您的建議。 –

-1

空函數在0(0爲整數)時返回false。

所以,你的代碼應該是

If(!isset($a)) 
{ 
    // code to run when $a not set or empty; 
} 
Elseif ($a==0) 
{ 
    //code to run when $a is equal 0 
} 
Else 
{ 
     //code to run in all other scenarios 
} 
+0

[空](http://us1.php.net/manual/en/function.empty.php)當值爲0時返回false作爲字符串或整數 –

+0

必須將空字符串視爲空。在你的情況下,這將是*所有其他場景* – sectus

0

代替這一點,並嘗試

If(!isset($a) || $a=='') 
{ 
// code to run when $a not set or empty; 
} 
Elseif ($a==0) 
{ 
    //code to run when $a is equal 0 
} 
Else 
{ 
     //code to run in all other scenarios 
} 
+0

你不能用'$ a =='''' – sectus

+0

替換'empty'爲什麼?空白和空白在我的知識中都是一樣的。你能否告訴我爲什麼我無法取代。 – wild

+1

http://php.net/empty – sectus

2
if (isset($a) && $a == 0) 
    { 
    //code to run when $a is equal 0 
    } 
elseif (empty($a)) 
    { 
    // code to run when $a not set or empty; 
    } 
else 
    { 
    //code to run in all other scenarios 
    } 
+0

我對這個感到興奮。但是當我嘗試它時,它不起作用。當你設置$ a =「」第一個代碼運行時,即使第二個代碼運行於 – user2395238

+0

@ user2395238,什麼?我發現你的邏輯完全不同於你的代碼。請更新您的答案。 – sectus

0

我找到了解決辦法:

if (!isset($a) || (empty($a) && $a!==0)) 
{ 
    //run code if $a is not set or is empty 
} 
elseif ($a===0) 
{ 
    //run code if $a is 0; 
} 
else 
{ 
    //all other scenarios 
}