views:

134

answers:

2

How does PHP read if statements?

I have the following if statements in this order

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
}

The code behaves randomly. It sometimes goes to the third if clause and gives me a success, while sometimes to the one of the first two if clauses when the input variables are constant.

This suggests me that I cannot code only with if statements.

+5  A: 

If you want to return only one of the results from many different if statements, use elseif, like this:

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
}
Randell
+5  A: 

It doesn't "behave randomly", it does what you tell it to do:

if ($a) {
    // do A
}

if ($b) {
    // do B
}

if ($c) {
    // do C
}

All three ifs are independent of each other. If $a, $b and $c are all true, it'll do A, B and C. If only $a and $c are true, it'll do A and C, and so on.

If you're looking for more "interdependent" conditions, use if..else or nested 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)
}

In the above only one action will get executed.

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

In the above both B and C might get done, but only if $a is false.

This, BTW, is pretty universal and not at all PHP specific.

deceze