WEB-230-028 | switch Statement | Lesson
Watch the video “Beginner PHP Tutorial – 028 – switch Statement” available under “Lesson Resources”.
The associated assignment may ask you to submit any work completed in the video. It is a goods idea to work along with the video and save any completed work.
ADDITIONAL INFORMATION
The switch statement is an alternative to the if-elseif-else statement.
Use the switch statement to select one of a number of blocks of code to be executed.
Syntax:switch (n) {
case value1:
//code to be executed if n=value1
break;
case value2:
//code to be executed if n=value2
break;
…
default:
// code to be executed if n is different from all labels
}
First, our single expression, n (most often a variable), is evaluated once. Next, the value of the expression is compared with the value of each case in the structure. If there is a match, the block of code associated with that case is executed.
Using nested if else statements results in similar behavior, but switch offers a more elegant and optimal solution.
Switch
Consider the following example, which displays the appropriate message for each day.
$today = ‘Tue’;
switch ($today) {
case “Mon”:
echo “Today is Monday.”;
break;
case “Tue”:
echo “Today is Tuesday.”;
break;
case “Wed”:
echo “Today is Wednesday.”;
break;
case “Thu”:
echo “Today is Thursday.”;
break;
case “Fri”:
echo “Today is Friday.”;
break;
case “Sat”:
echo “Today is Saturday.”;
break;
case “Sun”:
echo “Today is Sunday.”;
break;
default:
echo “Invalid day.”;
}
//Outputs “Today is Tuesday.”Try It Yourself
The break keyword that follows each case is used to keep the code from automatically running into the next case. If you forget the break; statement, PHP will automatically continue through the next case statements, even when the case doesn’t match.
default
The default statement is used if no match is found.
switch ($x) {
case 1:
echo “One”;
break;
case 2:
echo “Two”;
break;
default:
echo “No match”;
}//Outputs “No match”Try It Yourself
The default statement is optional, so it can be omitted.
Switch
Failing to specify the break statement causes PHP to continue to executing the statements that follow the case, until it finds a break. You can use this behavior if you need to arrive at the same output for more than one case.
$day = ‘Wed’;
switch ($day) {
case ‘Mon’:
echo ‘First day of the week’;
break;
case ‘Tue’:
case ‘Wed’:
case ‘Thu’:
echo ‘Working day’;
break;
case ‘Fri’:
echo ‘Friday!’;
break;
default:
echo ‘Weekend!’;
}
//Outputs “Working day”Try It Yourself
The example above will have the same output if $day equals ‘Tue’, ‘Wed’, or ‘Thu’.