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

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex