Grow your CSS skills. Land your dream job.

IF statements vs Switch statements

  • # December 9, 2010 at 10:30 am

    Is there really any big difference between


    if ($something == "cheese") {
    echo "Cheesey!";
    } else if ($something == "bacon" {
    echo "Smokey!";
    } else {
    echo "I'm hungry.";
    }

    and


    switch ($something) {
    case "cheese":
    echo "Cheesey!";
    break;
    case "bacon":
    echo "Smokey!";
    break;
    default:
    echo "I'm hungry.";
    }

    I’m just not sure why you would use one over the other.

    # December 9, 2010 at 10:34 am

    Nope, but I think the switch statement would be slightly faster.

    # December 9, 2010 at 10:54 am

    Ditto @jamy_za

    If you’re picky, here are some differences that I see:

    The first one has 134 characters, and the second has 154.

    The second one is more legible to me than the first, though it’s only preference.

    If I were to decide on which to use, I would pick the one that is most like the rest of my code.

    # December 9, 2010 at 11:27 am

    Shows what I know, I don’t think I’ve ever seen that second version before.

    # December 9, 2010 at 2:08 pm

    ‘switch’ looks much nicer, and is better if the ‘$something’ is a definate – like ‘cheese’ or ‘biscuits’

    ‘if’ statements can handle complicated expressions ‘$something>8′ (yeah, complicated I know :-) ). I’m not too sure that ‘switch’ can perform math functions. ‘if’ staments could get very complicated after 2-3 ‘elseif’ ‘s. I admit, I haven’t used switch, despite knowing of it’s existance. I should use it more often.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".