switch Statement
Switch Statement
The switch statement is used to execute one block of code among many options. It compares a variable with multiple cases and runs the matching case.
Syntax
switch (expression) {
case value1:
// code to execute
break;
case value2:
// code to execute
break;
default:
// code if no case matches
}
Example
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Friday":
echo "Weekend is near";
break;
case "Sunday":
echo "Holiday";
break;
default:
echo "Normal day";
}
?>
break Keyword
The break keyword is used to stop the execution of a loop or switch statement immediately. When break is used, the program exits the current structure and continues with the next line of code.
Example
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break;
}
echo $i . " ";
}
?>
---------------------------------------------------------------------
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>