理解PHP的if语句阅读方式

时间:2009-08-23 04:29:03

标签: php if-statement

PHP如何读取语句?

我按此顺序有以下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语句进行编码。

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分: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
}