ElseIf Statement Question

Discussion in 'PHP' started by T0PS3O, Mar 31, 2006.

  1. #1
    This sounds really n00bish to myself but anyway...

    I was just now coding an if statement and when I had finished it and re-read it, it looked kind of silly.

    Simplified it goes like this:

    
    $number = 6; // could be 3 in some cases
    $value = 300; // could be 175 in some cases
    if ($number >= 2.5 || $value >= 150) {
    echo 'Lower threshold reached...';
    } elseif ($number >= 5 || $value >= 250) {
    echo 'Higher threshold reached...';
    }
    // Possibly etc.
    
    PHP:
    In case of number = 6 and value = 300 then both will be true in principle.

    How will PHP handle this though? Will it stop parsing the rest of the if as soon as one statement is satisfied?

    In the case above I'd prefer (in this script) the elseif became true rather than the first one. So I should probably swap them around if indeed it stops parsing after one set of criteria is met.

    Weird how after tens of thousands of lines of code I never came across this before. Only ever made non-ambiguous if/elseif statements up until this point.
     
    T0PS3O, Mar 31, 2006 IP
  2. Nathan Malone

    Nathan Malone Well-Known Member

    Messages:
    369
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    110
    #2
    Yes, when doing elseif statements, PHP stops at the first one that evaluates to true.

    If you want it to do the second one even if the first one is true, then you can set it up as two if statements.
     
    Nathan Malone, Mar 31, 2006 IP
    exam likes this.
  3. T0PS3O

    T0PS3O Feel Good PLC

    Messages:
    13,219
    Likes Received:
    777
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks Nathan, suspected as much.

    BTW PMed you because I red repped you by accident, I am sooooo sorry. Meant to be green.

    Besides splitting them up in if statements I guess I could also use >= 2.5 AND < 5 to make sure the first one only gets set to true when it should be.
     
    T0PS3O, Mar 31, 2006 IP
  4. exam

    exam Peon

    Messages:
    2,434
    Likes Received:
    120
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Like you mentioned, just switch 'em around. If the first if statement evaluates to true, the following ones won't be evaluated. Kinda makes sense if you stop and think about the meaning of if ....... else ..... you only get to the else if the first if is not true..... then when you're at the else, lo and behold, there's another if statement. That's how if ... elseif works.
    
    if ($number >= 5 || $value >= 250) {
         echo 'Higher threshold reached...';
    
    // High threshold not reached, let's see if it reaches the lower one.
    } elseif ($number >= 2.5 || $value >= 150) {
         echo 'Lower threshold reached...';
    }
    PHP:
     
    exam, Mar 31, 2006 IP
    T0PS3O likes this.