SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Addict
    Join Date
    Sep 2000
    Location
    Ontario, Canada
    Posts
    320
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    case vs. if statements

    I was just wondering if there is an advantage of using a "case" over an "if" statement?

    I'm doing a query on a database that contains a user level of 0 to 4. In the header, I'd like to display some text depending on what user level the person is. So would this be a job for an "if" statement or a "case" statement?

    Any insight is appreciated.
    Jason Dulberg
    Extreme MTB
    http://extreme.nas.net

  2. #2
    SitePoint Wizard Defender1's Avatar
    Join Date
    Apr 2001
    Location
    My Computer
    Posts
    2,808
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    a case is pretty much the same.
    though it's a little more effecient when you want to run a lot of if's or elseif's in sucession.
    Defender's Designs
    I'm Getting Married!

    Not-so-patiently awaiting Harry Potter Book 7 *sigh*

  3. #3
    SitePoint Addict kunal's Avatar
    Join Date
    Oct 2000
    Posts
    307
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    well... case is easier then if when reading the code.. atleast for me.. it makes the code much cleaner.. and easier to debug... all the curly brackets in the if statement can get a lil confusing..
    i dunno...

  4. #4
    SitePoint Wizard Defender1's Avatar
    Join Date
    Apr 2001
    Location
    My Computer
    Posts
    2,808
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yea, it's easy to misplace a bracket.
    Defender's Designs
    I'm Getting Married!

    Not-so-patiently awaiting Harry Potter Book 7 *sigh*

  5. #5
    SitePoint Zealot alexk's Avatar
    Join Date
    Nov 2000
    Location
    Sydney, Australia
    Posts
    134
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    with relation to performance, it's all the same (at least it used to be like that in C++)... so just use what you like more

    i normally use case for 4+ cases %)

  6. #6
    will code HTML for food Michel V's Avatar
    Join Date
    Sep 2000
    Location
    Corsica
    Posts
    552
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I use it for multi-purpose PHP files, like switch($action) and case "update", case "edit", etc
    It's a very efficient way to group multiple PHP files into just one.

    But for casual if statements, like 1 to 4 or 5 choices, I'd stick to if.
    [blogger: zengun] [blogware contributor: wordpress]

  7. #7
    SitePoint Columnist Skunk's Avatar
    Join Date
    Jan 2001
    Location
    Lawrence, Kansas
    Posts
    2,066
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'd be surprised if there was a speed advantage for one method over the other - it's all a case of personal preference really. Case is handy if there are lots of possible options and each requires different logic. For example, most of the scripts I write use an $action variable (set in the query string) to tell the script what to do. I can quickly and easily structure the script with a switch statement:
    PHP Code:
    <?php
    switch ($action) {

    case 
    'addnews':
        
    // Code for adding news
        
    exit;

    case 
    'editnews':
        
    // Code for editing news
        
    exit;

    case 
    'search':
        
    // Code for the search facility
        
    exit;

    case 
    'archive':
        
    // Code for news archive
        
    exit;

    default:
        
    // Code for if no action is specified, or action didn't match the above

    ?>
    Another handy attribute of switch is the fact that program execution can "fall through" to the next case statement if you don't include an exit or break. I've never had a reason to use this but I can imagine it could save a lot of time in some situations.

  8. #8
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just cause I was curious I ran an apache benchmark test on two files one using if elseif and once using switch() here are the results:

    test1.php
    PHP Code:
    <?php
    $action 
    "addnews";
    switch (
    $action) {

    case 
    'addnews':
        print 
    "addnews";
        
    // Code for adding news
        
    exit;

    case 
    'editnews':
        print 
    "editnews";
        
    // Code for editing news
        
    exit;

    case 
    'search':
        print 
    "search";
        
    // Code for the search facility
        
    exit;

    case 
    'archive':
        print 
    "archive";
        
    // Code for news archive
        
    exit;

    default:
        print 
    "default";
        
    // Code for if no action is specified, or action didn't match the above
        
    }
    ?>

    test2.php
    PHP Code:
    <?php
    $action 
    "addnews";

    if(
    $action == 'addnews') {
        print 
    "addnews";
        
    // Code for adding news
        
    }
    elseif (
    $action == 'editnews') {
        print 
    "editnews";
        
    // Code for editing news
        
    }

    elseif (
    $action == 'search') {
        print 
    "search";
        
    // Code for the search facility
        
    }

    elseif (
    $action == 'archive') {
        print 
    "archive";
        
    // Code for news archive
        
    }

    else {
        print 
    "default";
        
    // Code for if no action is specified, or action didn't match the above
        
    }
    ?>

    Results for test1.php
    Code:
    Server Software:        Apache/1.3.12                                      
    Server Hostname:        www.domain.com
    Server Port:            80
    
    Document Path:          /test1.php
    Document Length:        7 bytes
    
    Concurrency Level:      100
    Time taken for tests:   1.611 seconds
    Complete requests:      1000
    Failed requests:        0
    Total transferred:      254762 bytes
    HTML transferred:       7021 bytes
    Requests per second:    620.73
    Transfer rate:          158.14 kb/s received
    
    Connnection Times (ms)
                  min   avg   max
    Connect:        0     2    10
    Processing:    14   149   283
    Total:         14   151   293
    Results for test2.php
    Code:
    Server Software:        Apache/1.3.12                                      
    Server Hostname:        www.domain.com
    Server Port:            80
    
    Document Path:          /test2.php
    Document Length:        7 bytes
    
    Concurrency Level:      100
    Time taken for tests:   1.622 seconds
    Complete requests:      1000
    Failed requests:        0
    Total transferred:      254762 bytes
    HTML transferred:       7021 bytes
    Requests per second:    616.52
    Transfer rate:          157.07 kb/s received
    
    Connnection Times (ms)
                  min   avg   max
    Connect:        0     3    12
    Processing:    14   149   159
    Total:         14   152   171


    As you can see the results are so minimal that I think Skunk hit the nail on the head, and it all boils down to personal preference.
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  9. #9
    code addict Abstraction's Avatar
    Join Date
    Apr 2001
    Location
    Des Moines, IA
    Posts
    346
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The way I see it is the case is less typing and more readable than the if/else.

  10. #10
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Less typing and more readable doesn't mean better, for you personally its better, but the tests don't lie, and there is no reason to change anything if you happen to use if/elseif. There isn't enough of a difference.
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  11. #11
    code addict Abstraction's Avatar
    Join Date
    Apr 2001
    Location
    Des Moines, IA
    Posts
    346
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Originally posted by freddydoesphp
    Less typing and more readable doesn't mean better, for you personally its better, but the tests don't lie, and there is no reason to change anything if you happen to use if/elseif. There isn't enough of a difference.
    I never said one was better than the other or that one should go and change their code. ;-)

  12. #12
    SitePoint Zealot alexk's Avatar
    Join Date
    Nov 2000
    Location
    Sydney, Australia
    Posts
    134
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    j/c

    freddydoesphp, I'm just curious about the results of above tests with
    $action = "default";
    Last edited by alexk; Jul 31, 2001 at 14:48.

  13. #13
    SitePoint Addict
    Join Date
    Sep 2000
    Location
    Ontario, Canada
    Posts
    320
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow... thanks for all your comments.... I didn't expect this much attention to the question.

    I ended up using a case statement - since it appears that speed isn't a factor between the two methods, I felt like trying something different... I've never used the case before so this is my first.

    Thanks to everyone for all your comments!
    Jason Dulberg
    Extreme MTB
    http://extreme.nas.net

  14. #14
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well I agree that efficiency of execution is *not* a significant concern 80% of time (results of independent research conducted at the freaky laboratories). However, well written code is self documenting code. This includes things like giving variables meaningful names that relate the the data they represent. It also means chosing the appropriate control structure that best represents the type of logic you, the programmer, have in mind.

    For example, there several ways you could iterate through an array that are all technically feasable:
    Example 1: the traditional approach to traversing an array in many languages
    PHP Code:
    $myArray = {012345};
    $count =  count($myArray);
    for(
    $i 0$i $count; $ i++) {
       echo 
    $myArray[$i];

    Example 2: technically valid but more obscure way of doing the same thing (harder to glean the logic on first reading).
    PHP Code:
    $myArray = {012345};
    while(! empty(
    $myArray[$i])) {
       echo 
    $myArray[$i++];

    But the cleanest, most lucid way of writing this (IMHO) because it is self documenting (the code clearly explains the programmers thinking):
    PHP Code:
    $myArray = {012345};
    foreach(
    $myArray AS $element) {
       echo 
    $element;

    As others have stated already, on top of the fact that it is easier to format and read a switch structure over a long if/elseif/else stucture. However, the point I was getting at with my code above is that there are times when the switch control structure illustrates the purpose of the code and the architecture of the script. Skunk's example is the classic example of creating a switchboard architecture. See http://www.fusebox.org/. They call their architecture fusebox, but I think that the metaphore of a switchboard is more suitable. I have been working on a member control panel for a site and the switchboard architecture is perfect for this. Here is a pseudo-mumbo-jumbo explaination (hehe - the last time I wrote pseudo-mumbo-jumbo, no one understood what I was going on about):
    Code:
    IF the user's session is not valid THEN
       redirect user to login page
       EXIT the script
    END IF
    
    include the file with the member control panel header and navigation html
    
    SWITCH ON HTTP_GET_VARS[action]
       CASE OF "foo"
          include file "dofoo.php"
          break
       CASE OF "bar"
          include file "dobar.php"
          break
       DEFAULT ACTION
          include file "default.php"
    END SWITCH
    
    include the file with the member contol panel footer html
    EXIT
    So hopefully not only is the code I would write to impliment that design neat and readable, but it reflects the architecture of the member control panel application. The control panel pages are generated by sending all requests through a index.php which acts as a switchboard. The designer can also, hopefully, follow the logic of the application and see how his/her client side code will fit in. So hopefully it is a clean architecture for all parties to follow.
    Last edited by freakysid; Aug 1, 2001 at 06:52.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •