In PHP, the switch statement is a control structure that allows the program to execute different blocks of code based on the value of a certain variable or expression. It is an alternative to using multiple if-else statements, and can make code more readable and easier to maintain.
The syntax of the switch statement in PHP is as follows:
switch (expression) { case value1: // code to be executed if expression equals value1 break; case value2: // code to be executed if expression equals value2 break; case value3: // code to be executed if expression equals value3 break; ... default: // code to be executed if none of the cases match expression break; }
Here’s how the switch statement works:
- The switch keyword is followed by the expression that you want to evaluate.
- The expression is then compared to each case value one by one, until a match is found.
- If a match is found, the code inside the corresponding case block is executed. The break statement is used to exit the switch block after the code is executed.
- If none of the cases match the expression, the code inside the default block is executed.
Here’s an example of the switch statement in action:
<?php $day = "Monday"; switch ($day) { case "Monday": echo "Today is Monday"; break; case "Tuesday": echo "Today is Tuesday"; break; case "Wednesday": echo "Today is Wednesday"; break; case "Thursday": echo "Today is Thursday"; break; case "Friday": echo "Today is Friday"; break; default: echo "It's the weekend!"; break; } ?>
Output:
Today is Monday
In the above code, we have used the switch statement to check the value of the $day
variable. Since $day
is “Monday”, the code inside the first case block is executed, which prints “Today is Monday” using the echo
statement.