2009-08-23 54 views
0

PHP如何讀取if語句?瞭解PHP的閱讀方式

我有以下的,如果順序

if ($number_of_figures_in_email < 6) { 
     -- cut: gives false 
} 


if($number_of_emails > 0) {                   
     -- cut: gives false 
} 

if ($number_of_emails == 0) { 
    -- cut: gives true 
} 

語句代碼的行爲隨機。它有時會轉到第三個if子句,並使我獲得成功,有時甚至會在前兩個if子句中的一個輸入變量不變時生效。

這表明我不能只用if語句編碼。

+0

謝謝你的回答! – 2009-08-23 07:22:46

回答

6

它並不「隨意行爲」,它做什麼,你告訴它做:

if ($a) { 
    // do A 
} 

if ($b) { 
    // do B 
} 

if ($c) { 
    // do C 
} 

全部三個ifs是相互獨立的。如果$a,$b$c都是true,它將執行A,B和C.如果只有$a$c爲真,則它將執行A和C等等。

如果您正在尋找更多的「相互依存」的條件下,使用if..else或嵌套ifs

if ($a) { 
    // do A and nothing else 
} else if ($b) { 
    // do B and nothing else (if $a was false) 
} else if ($c) { 
    // do C and nothing else (if $a and $b were false) 
} else { 
    // do D and nothing else (if $a, $b and $c were false) 
} 

在上面只有一個動作都會得到執行。

if ($a) { 
    // do A and stop 
} else { 
    // $a was false 
    if ($b) { 
     // do B 
    } 
    if ($c) { 
     // do C 
    } 
} 

在上面的B和C都可能完成,但只有當$a爲假。

這,BTW,是相當普遍的,並沒有在所有的PHP特定。

5

如果你只想返回從許多不同的結果之一if語句,使用elseif,像這樣:

if ($number_of_figures_in_email < 6) { 
     -- cut: gives false 
} 
elseif($number_of_emails > 0) {                   
     -- cut: gives false 
} 
elseif ($number_of_emails == 0) { 
    -- cut: gives true 
}