Skip to main content

PHP if else - proper use of "else”



A professor told me long ago to use else when "chaining" multiple conditions in a series (I was still learning). Now that I've been tinkering with several frameworks and CMS years later, I find it quite amusing that what I was taught to do isn't necessarily so.





I was taught to use else in between a series of conditions:







function double(param){

if(param==1){

return param+=1;

}

else

if(param==2){

return param+=2;

}

else{

return false;

}

}







Nowadays, I seem to see this, which I was warned long ago NOT to do:







function double(param){

if(param==1){

return param+=1;

}

if(param==2){

return param+=2;

}

return false;

}







This sample code might not work, but the idea is there: Is it necessary to use else in between every condition? If so (or not so), what should I look out for when using either way? There must be something that caused my professor to tell me such thing.


Comments

  1. It is not necessary to use else, as the control flow returns from the function immediately at the point of the return keyword.

    Further, I find using else when there is a return unnecessarily confusing, and so would prefer alternative 2 in all cases.

    ReplyDelete
  2. Using else or not using it mean two different things.

    When you wish to test a series of conditions where at most one may be true, use else or else if. When one condition evaluates true, the code in the block is executed and then the entire if-else construct is exited.

    When more than one condition may be true, using else will preclude other conditions from evaluating to true, and so it would be wrong to use an else in this situation.

    Edit: I now see you are referring to the specific case where each clause contains a return statement. In this case it is probably better to use an else or elseif to make it clear that the if-else construct behaves in the first manner - ie. at most one condition may execute.

    ReplyDelete
  3. It's really just a matter of opinion.

    It's not necessary to use else in a case such as this, however your professor may have been describing a different case, or perhaps he was simply having you do it for emphasized/forced clarity.

    First of all, it's my opinion that returning different data types from the same function is generally bad style, but having said that, take your example:

    function double($param) {
    if ($param == 1) {
    return $param + 1;
    } else if ($param == 2) {
    return $param + 1;
    } else {
    return false;
    }
    }


    Now imagine a similar example, except it doesn't return each time:

    function double($param) {
    $returnMe = 0;

    if ($param == 1) {
    $returnMe = $param + 1
    } else if ($param == 2) {
    $returnMe = $param + 2;
    } else {
    $returnMe = false;
    }

    return $returnMe;
    }


    This may seem trivial (and in the examples provided it largely is), you can see that the else really does make a difference.

    In forcing everything to have an else like he did, he was probably just trying to provide some consistency in style (which I'd argue is good for newcomers).

    Of course, you are right, in the case you presented, having the else was unnecessary. Whether or not it's bad or good is really just a matter of opinion.

    ReplyDelete
  4. I think it's a good practice, becouse the flow would follow down if you forget the return clause (leading to hard-to-find bugs)

    Anyway, the else clause may be too verbose in some situations, so you can use elseif:

    <?php
    if ($a > $b) {
    return "a is bigger than b";
    } elseif ($a == $b) {
    return "a is equal to b";
    } else {
    return "a is smaller than b";
    }
    ?>

    ReplyDelete
  5. Yes. Why? Because these conditions are based on the same variable and only one can be met. For this reason, if you use elseif (PHP) or else if (JavaScript), you will improve code visibility and possibly avoid some future errors.

    Your code in PHP

    Your code in PHP would look like this:

    function double($param){
    if($param==1){
    return $param+=1;
    }
    elseif($param==2){
    return $param+=2;
    }
    else{
    return false;
    }
    }


    or, using switch counterpart:

    function double($param){
    switch ($param) {
    case 1:
    return $param+=1;
    case 2:
    return $param+=2;
    default:
    return false;
    }
    }


    Your code in JavaScript

    In JavaScript it would look like this:

    function double($param){
    if($param==1){
    return $param+=1;
    }
    else if($param==2){
    return $param+=2;
    }
    else{
    return false;
    }
    }

    ReplyDelete
  6. Scenario 1

    if ($one) {
    doA();
    }
    if ($two) { // ALWAYS check this block - it is not attached to anything
    doB();
    }

    Truth table:

    | $one True | $one False
    ------------+-----------+------------
    $two True | A and B | B only
    $two False | A only | none


    Scenario 2

    if ($one) {
    doA();
    }
    else if ($two) { // ONLY check this block if $one is false!
    doB();
    }

    Truth table:

    | $one True | $one False
    ------------+-----------+------------
    $two True | A only | B only
    $two False | A only | none


    As you can see in the truth tables, the two scenarios are not the same. So, whether to use if..else or if..if is not just a matter of semantics or taste, it has an actual functional difference.

    In the case of returns inside of an if, it will exit the function entirely and therefore it is a special case where the result is the same as an else-if.

    ReplyDelete
  7. it really depends on the flow of your codes...
    sometimes you need to use separate if(s), and sometimes you need to use if(s) and else(s)...
    but for the sake of the example you added. personally, I'd select the first one you wrote because its more efficient and easier to read and understand. perhaps there are other factors and points but that's how I see it and that's why I chosen the first one..

    one more thing to add.. is that if you use the second one the compiler will always execute the second "if", if the $param was containing a different value other than "1" or "2".

    ReplyDelete
  8. You may fancy this scenario I spotted not too long ago on Apple's website

    switch(true) {
    case foo == bar:
    break;
    case foo > 5:
    break;
    case foo > 10:
    case bar > 5:
    break;
    }


    You get the idea. I believe all compilers break this down to if/else code, but I like the flexibility of controlling where the break statements are.

    ReplyDelete

Post a Comment

Popular posts from this blog

Wildcards in a hosts file

I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly.