Locked lesson.
About this lesson
Exercise files
Download this lesson’s related exercise files.
Switch.docx58.9 KB Switch - Solution.docx
59.5 KB
Quick reference
Switch
Switch is another type of conditional statement.
When to use
Use Switch when you have several "cases" to test against.
Instructions
The format of a switch is this:
switch (x) {
case1:
// do stuff;
break;
case2:
// do stuff;
break;
default:
// do stuff;
}
You can have as many "cases" as you like, the more the better (otherwise just use an if/elseif statement).
Here's a switch in action:
$car = "ford";
switch ($car) {
case "ford":
echo "You like ford";
break;
case "chevy":
echo "You like chevy";
break;
default:
echo "I don't know what you like!";
}
Hints & tips
- Switch is another type of conditional statement
- Use it to test cases
- Be sure to 'break' after each case, but you don't have to for the last default
Lesson notes are only available for subscribers.