Switch allows to execute code on basis of condition matched to available cases, else it executes default block. It works similar like if else if else.

Syntax

switch(condition){
 case label:
 // set of statements
 break;
case label:
 // set of statements
 break;
default:
 // set of statements
}

Example

<?php
$day = 2;
switch($day){
 case 1:
 echo "Monday";
 break;
case 2:
 echo "Tuesday";
 break;
case 3:
 echo "Wednesday";
 break;
case 4:
 echo "Thursday";
 break;
case 5:
 echo "Friday";
 break;
default:
 echo "Weekend";
}
?>

Switch matches the given input with case labels. If label is matched, executes the following code statements. Default block must comes in end with no break keyword.

Break Keyword

Break is used to transfer program execution out of switch block, to stop matching of different available case labels, It saves execution time and increase speed of program execution.

In default their is no break keyword, because it is the last block in switch, Hence it is not required in default at all.

Multiple case labels or common code blocks

<?php
$day = 2;
switch($day){
case 1:
case 2:
case 3:
case 4:
case 5:
 echo "Weekdays (Work Hard!)";
 break;
default:
 echo "Weekend Enjoy";
}
?>

PHP allows to use multiple labels for single code block. If any of the case label gets matched, the related code statements gets executed.

Default keyword

If no case labels matches, then default statements executes. It should be the last block of switch.
It It is like else of if in switch.

Default can be placed anywhere in switch, but this practice is not recommended.