2011-06-12 180 views
3

我有我的IF語句的問題,它總是TRUE,雖然這是不正確的。我使用OR運算符,因爲我想在IF語句中捕獲兩種可能的場景。或PHP IF語句

數組字符串ad_status是「1」,但使用下面的-3返回,我期待IF爲假。如果我從IF中刪除OR和第二條語句,那麼IF的結果是正確的。

我做錯了什麼?謝謝。

if(($getadstatus['ad_status'] != "1" || $getadstatus['ad_status'] != "4")) 
    { 
     return -3; 
     exit; 
    } 

附加: 我想要做的是出口的函數(在這裏完全沒見過),如果ad_status不等於1或4。如果它等於比1或4,IF語句之外的任何其他值應該返回TRUE並退出。 ad_status可以是0到4之間的任何值。

+2

廣告狀態*總是*(不等於「1」*或*不等於「4」),因爲它一次不能有兩個值。你能重申你想要建立的狀況嗎? – 2011-06-12 10:11:28

+0

該聲明將始終返回true。 (如果$ getadstatus ['ad_status']'是1,它不能同時是4等等)你想達到什麼目的? – 2011-06-12 10:12:14

+1

humm,好的,我想我明白了。我試圖太聰明。我想用單個IF語句來檢查兩個不相關的條件。如果ad_status不等於1或4,則返回-3並退出該函數。 – Damo 2011-06-12 10:13:13

回答

8

你所說的是,這是not 1 OR是not 4應返回true任意值。

爲 '1' 你得到它轉換爲

if(false || true) 

這是ofcourse真正的聲明

if(1 != 1 || 1 != 4) 

你需要的是:

if(!($value == 1 || $value==4)) 

這是一樣的(de Morgan's law

if($value != 1 && $value != 4) 
2

這裏沒有錯誤。

如果ad_status == 1那麼你的第二個條件將讓你進入。如果

$getadstatus['ad_status'] != "4" 

因此,真正的你將得到return -3;

,如果我得到你想你應該使用什麼AND

if ($a!= 1 AND $a!= 4) 
+1

該死的我需要鍵入更快:) – onigunn 2011-06-12 10:12:55

+0

我真的失去了一些時間來了解OP想要什麼大聲笑..這就是爲什麼我花了3分鐘回覆:) – dynamic 2011-06-12 10:14:05

2

您查看:

ad_status != 1 -> FALSE 
ad_status != 4 -> TRUE 

if (FALSE OR TRUE)總是TRUE

要成爲你所期望的,更換或與AND:

if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4")) 
{ 
    return -3; 
    exit; 
} 
2

這將永遠是真實的,同時這兩個「1」和「4」的任何值不能爲。

2

您應該使用&&運營商,因爲使用!=。如果你想使用||,你可以這樣寫:

if (!($getadstatus['ad_status'] == "1" || $getadstatus['ad_status'] == "4"))

2

你想用& &

if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4")) 
{ 
    return -3; 
    exit; 
} 
1

我個人比較喜歡in_array代替或者在IF語句中。例如:

$array = array(1,4); 

if (!in_array($getadstatus['ad_status'], $array)) { 
// do whatever 

} 
0

赫姆,確定我想我明白了。我試圖太聰明。我想用單個IF語句來檢查兩個不相關的條件。如果ad_status不等於1或4,則返回-3並退出該函數。

好了,沒問題,可以表達,只是制定喜歡你寫的:

$status = $getadstatus['ad_status']; // assign a variable as it makes things easier to read. 
if (!($status==1 || $status==4)) 
{ 
    return -3; 
} 

所以!(不)應該是全部或比較,因爲你在你的句子寫了。這可能是代碼,你最初的想法。但由於順序很重要,因此在使用not(!)運算符之前,您的條件的其他部分需要在括號內進行計算。

加了:

的更多的子條件的條件或表達式的一部分,更復雜它得到。但是,越是經常制定複雜的條件,你越會得到更好的條件。爲了訓練,你總是可以拆分爲多行條件和分配標籤(變量)的一部分:

$status = $getadstatus['ad_status']; 
$statusIs1or4 = $status==1 || $status==4; 
$statusIsNot1or4 = !$statusIs1or4; 
if ($statusIsNot1or4) return -3; 

對於生產代碼,這可能是用眼過度,但它始終是作者的選擇如何寫東西,你可以做任何語言允許的。