PHP switch Statement

The switch statement in PHP is used to perform different actions based on different conditions, similar to a series of if...elseif statements. It is particularly useful when you need to compare the same expression to several different values.

Syntax:

switch (expression) { case value1: // Code to execute if expression == value1 break; case value2: // Code to execute if expression == value2 break; // You can have any number of case statements default: // Code to execute if expression doesn't match any case }

Key Points:

  • expression is evaluated once and compared to each case value.

  • break prevents the code from continuing to the next case.

  • default is optional and executes if no case matches.

Example:

$day = "Monday"; switch ($day) { case "Monday": echo "Start of the work week."; break; case "Friday": echo "Last working day of the week."; break; case "Saturday": case "Sunday": echo "It's the weekend!"; break; default: echo "Midweek day."; }

Output:

Start of the work week.