About
A switch is a multi-way conditional branch that permits to control the flow
Syntax
There is basically two syntax:
- the value_switch where the possibilities are scalar values
- the expression_switch where the possibilities are expressions
Value Switch
Php:
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
default:
echo "i is not equal to 0 or 1";
}
Sql
CASE Promotions."Promo Subcategory"
WHEN 'TV commercial' then 'Commercial'
WHEN 'TV program sponsorship' then 'Sponsor'
ELSE 'Default'
END
Expression Switch
Php:
switch (true) {
case $start - $offset === 1:
print "A";
break;
case $start - $offset === 2:
print "B";
break;
}
Sql:
CASE WHEN "Sales Facts"."Amount Sold" > 600000 THEN 'Big'
WHEN "Sales Facts"."Amount Sold" > 300000 THEN 'Middle'
ELSE 'Small' END
Fall through behavior
The switch statement has fall through behavior therefore the break is important.
If you omit the break from a case, and that case matches or runs, execution will continue to the next case.
Without break
color = "green"
switch (color) {
case "blue":
console.log("blue");
case "green":
console.log("green");
case "red":
case "orange":
console.log("red or orange");
default:
console.log("default");
}
- Result: You will see all console output from the green case
With ''break'
color = "green"
switch (color) {
case "blue":
console.log("blue");
break;
case "green":
console.log("green");
break;
case "red":
case "orange":
console.log("red or orange");
break;
default:
console.log("default");
}
- Result: you will see only one output