PHP

switch Statement

PHP / switch Statement

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!";
}
?>

Technology
PHP
want to connect with us ?
Contact Us