2009-08-23 55 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 
}