php
2011-06-10 30 views 0 likes 
0

我知道這是簡單的PHP邏輯,但它只是將無法正常工作......PHP如果不等於(!=)和or(||)問題。爲什麼不工作?

$str = "dan"; 
if(($str != "joe") 
    || ($str != "danielle") 
    || ($str != "heather") 
    || ($str != "laurie") 
    || ($str != "dan")){   

echo "<a href='/about/".$str.".php'>Get to know ".get_the_author_meta('first_name')." &rarr;</a>"; 
        } 

我在做什麼錯?

+7

你有什麼期望發生請描述? – lam3r4370 2011-06-10 19:15:32

+0

怎麼回事? – 2011-06-10 19:15:49

+0

另外,你的變量被設置爲'dan',你檢查變量是不是丹(或其他),並回應一些東西。我認爲你期望看到信息,用echo輸出,但你的變量是'dan'。 – lam3r4370 2011-06-10 19:18:35

回答

38

我不完全確定你想要什麼,但該邏輯將始終評估爲true。您可能需要使用AND(& &),而不是OR(||)

所測試過的最遠的語句是($str != "danielle")和只有兩種可能的結果是PHP儘快進入塊作爲聲明成真。

這是第一個:

$str = "dan"; 

$str != "joe" # true - enter block 
$str != "danielle" #ignored 
$str != "heather" #ignored 
$str != "laurie" #ignored 
$str != "dan" #ignored 

這是第二次:

$str = "joe"; 

$str != "joe" # false - continue evaluating 
$str != "danielle" # true - enter block 
$str != "heather" #ignored 
$str != "laurie" #ignored 
$str != "dan" #ignored 

如果OR改爲然後保持評估,直到返回false:

$str = "dan"; 

$str != "joe" # true - keep evaluating 
$str != "danielle" # true - keep evaluating 
$str != "heather" # true - keep evaluating 
$str != "laurie" # true - keep evaluating 
$str != "dan" # false - do not enter block 

雖然解決方案不能很好地擴展,但您應該保留一個排除列表數組並檢查它:

$str = "dan"; 
$exclude_list = array("joe","danielle","heather","laurie","dan") 
if(!in_array($str, $exclude_list)){   
    echo " <a href='/about/".$str.".php'>Get to know ".get_the_author_meta('first_name')." &rarr;</a>"; 
} 
+0

只是好奇,但不會&&表示他們都必須是正確的?基本上完整的函數將得到作者的名字,只爲那些沒有被上述命名的作者做... – 2011-06-10 19:16:39

+1

是的,所以如果** $ str不等於「joe」並且$ str不等於「danielle」$ str不等於「heather」**等。 – Gazler 2011-06-10 19:18:21

+0

對於!=「合適」意味着它不是指定的作者之一。 – Amber 2011-06-10 19:19:28

2

試試這個

$str = "dan"; 

if($str == "joe" || $str == "daniella" || $str == "heather" || $str == "laurine" || $str == "dan"){ ... } 
5

基於對格雷澤的回答您的評論,它看起來像你想進入if塊時$str不是列出的名字之一。

在這種情況下,如果你把它寫成

if(!(($str == "joe") || ($str == "danielle") || ($str == "heather") || ($str == "laurie") || ($str == "dan"))) 

這實際上讀取爲「如果不是這些人之一......」給別人看你的代碼,這將是更具可讀性。 即相當於他們是相當於被稱爲德摩根的法律邏輯稍微不太明顯的

if(($str != "joe") && ($str != "danielle") && ($str != "heather") && ($str != "laurie") && ($str != "dan")) 

的事實。

7

歡迎布爾邏輯:

$str = 'dan' 

$str != "joe" -> TRUE, dan is not joe 
$str != "danielle" -> TRUE, danielle is not dan 
$str != "heather") -> TRUE, heather is not dan 
$str != "laurie" -> TRUE, laurie is not dan 
$str != "dan" -> FALSE, dan is dan 

布爾邏輯真值表如下所示:

和:

TRUE && TRUE -> TRUE 
TRUE && FALSE -> FALSE 
FALSE && FALSE -> FALSE 
FALSE && TRUE -> FALSE 

或:

TRUE || TRUE -> TRUE 
TRUE || FALSE -> TRUE 
FALSE || TRUE -> TRUE 
FALSE || FALSE -> FALSE 

你的說法歸結Ť ○:

TRUE || TRUE || TRUE || TRUE || FALSE -> TRUE 
10

另一種方法是

$name = 'dan'; 
$names = array('joe', 'danielle', 'heather', 'laurie', 'dan'); 

if(in_array($name,$names)){ 
    //the magic 
} 
相關問題