如何读取if语句?
我有以下如果按这个顺序陈述的话
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语句进行编码。
发布于 2009-08-23 05:14:11
它不是“随机行为”,而是做你让它做的事情:
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为false。
这,BTW,是相当普遍的,完全没有PHP的特定。
发布于 2009-08-23 04:31:38
如果您只想返回来自许多不同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
}https://stackoverflow.com/questions/1317755
复制相似问题