The switch case statement can be very usefull and makes your code more readable if you need to make a lot of decisions with the if - elseif - else statement. Let's suppose the following example where we use the if-else sollution:
Code:
In this code we compare the same variable with many different values using the if statement. However this is the case where we could use the switch - case control strucure as well like this:
Code:
Although the switch sollution doesn't result a shorter code but it is a bit easier to understand. However you have to take care of the break statements which works as a code block terminator.
This example is not exactly the same as the "if" version as for example in case of $x=10 this code prints nothing. To solve this we can extend our switch statement.
To solve the previous problem we can extend our code with a default part. The code in this block works as the else block in case of the if satetement. So the complete switch statement will look like this:
Code:
The default case matches anything that wasn't matched by the other cases, and should be the last case. statement.
No comments:
Post a Comment