What is the difference between Switch, Case and If, Else?

Asked

Viewed 24,948 times

24

I’d like to know the difference between switch .. case and if .. else.

Which offers a better "performance"?

  • 2

    I think my answer compares the two variants in terms of functionality: http://answall.com/a/57792/129; in relation to performance I think it is derisory. But for reference: http://stackoverflow.com/questions/3399755/if-versus-switch

2 answers

24


In short, the control structure switch is a if to operate on the same input variable or expression.

There is not exactly a comparison between the two to ascertain their performance given the goal of each distinct being.

What exists is the correct use of the most appropriate control structure for our goal.

switch

We should use when we want to compare the same variable or expression with several options:

The instruction switch is similar to a number of instructions IF on the same expression. On many occasions, you may want to compare the same variable (or expression) to many different values by executing a different piece of code depending on what value it fits. This is exactly what the instruction switch ago.

Example in Ideone.

switch($a) {
    case 1: {
        echo 'Variável A é igual a 1';
        break;
    }
    case 2: {
        echo 'Variável A é igual a 2';
        break;
    }
    default: {
        echo 'A Variável A não é igual a 1 nem igual a 2';
    }
}

We’re buying $a with a number of different values.

if

We should use when we want to carry out a series of separate checks.

The construction if is one of the most important features of many languages, PHP include. It allows conditional execution of code fragments.

Example in Ideone.

if ($a > $b) {
    echo "A é maior que B";
}
else if ($a < $b) {
    echo "A é menor que B";
}
else if ($a == $b) {
    echo "A é igual a B";
}
else {
    echo "A é alguma coisa não comparável com B";
}

We are making use of different expressions to execute code accordingly.

Comparison

In order to compare the two, we would have to use one of them less appropriately:

Use switch less appropriately:

Example in Ideone.

switch($a) {
    case ($a > $b): {
        echo "A é maior que B";
        break;
    }
    case ($a < $b): {
        echo "A é menor que B";
        break;
    }
    case ($a == $b): {
        echo "A é igual a B";
        break;
    }
    default: {
        echo "A é alguma coisa não comparável com B";
    }
}

echo PHP_EOL;

switch("batata frita") {
    case ($a > $b): {
        echo "A é maior que B";
        break;
    }
    case ($a < $b): {
        echo "A é menor que B";
        break;
    }
    case ($a == $b): {
        echo "A é igual a B";
        break;
    }
    default: {
        echo "A é alguma coisa não comparável com B";
    }
}

We can observe that the input value does not matter when we use the switch like a if were it.

Use if less appropriately:

Example in Ideone.

if ($a == 1) {
    echo 'Variável A é igual a 1';
}
else if ($a == 2) {
    echo 'Variável A é igual a 2';
}
else {
    echo 'A Variável A não é igual a 1 nem igual a 2';
}

We can observe that we are comparing the same variable with different values, making use of a control structure designs to perform much more complex comparisons than this.

  • 2

    Thank you for the reply, very well explained!

  • 1

    Just to be clear and, who knows how interesting it is to adapt the answer: the input value of switch interest and a lot. What happens that $a being 1, PHP treats the entry as true and, in this way, will search us case the expression that is true. Just invert the values of $a and $b for see what happens. Being $a zero, PHP treats as false, seeking us case the first false expression ($a > $b), displaying an unexpected result. The second example continues to work because non-empty string is considered true by PHP.

8

The comparison should be made in fact between switch and if. The case is part of the construction of switch to identify each block. The else has a similar shape but works differently.

The switch is used to compare value equality with an expression (usually a variable is used). It can’t do other types of comparison or relationship between data. It’s quite simple, you set up an expression on switch which is one side of the comparison and in each case will be placed a value - fixed, has to be literal - that will be the other side of the comparison. He will try to evaluate all the values that establish this equality. To avoid all following evaluations it is necessary to say this explicitly in the code , probably with break.

The if evaluates any condition, it is possible to use complex expressions establishing comparisons and relationships that in the end result in true or false. If the result is true, the next code block will be executed, otherwise the code block set in else. There’s still the question of elseif which has already been mentioned in another question. Running a block, it does not evaluate the condition and much less executes the others ahead.

The trend is the switch be slightly faster because it is probably implemented with a table of lookup. And the comparison would only be fair of no if the expression also makes an expression of simple equality. Any other expression will render the comparison meaningless since they do different things. Including there compare with different expressions. So you can compare the performance of these examples:

switch ($var) {
    case 0:
        //faz algo
        break;
    case 1:
        //faz algo
        break;
    case 2:
        //faz algo
        break;
    case 3:
        //faz algo
        break;
}

And

if ($var == 0) {
    //faz algo
} elseif ($var == 1) {
    //faz algo
} elseif ($var == 2) {
    //faz algo
} elseif ($var == 3) {
    //faz algo
}

In other ways, it’s not possible.

Even if it makes a difference, it will be very small, essentially insignificant, especially when it comes to PHP. It is not a recommended concern, on the contrary, the option of one or the other should be by necessity. The switch help indicate that you are looking for a value among a list of them. (I don’t have time to do tests right now but it is certain that they will be virtually identical).

Since PHP 5.5 in some cases may be more interesting to do ['stack', 'overflow'][$x] than

switch ($x) {
    case 0: 
        echo 'stack';
        break;
    case 1:
        echo 'overflow';
        break;
}

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.