How to use the switch statement in PHP?

Member

by shyann , in category: PHP General , a year ago

How to use the switch statement in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by wilmer.lemke , a year ago

@shyann 

In PHP, the switch statement is used to perform different actions based on different conditions. Here's the basic syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
switch (expression) {
    case value1:
        //code to execute if expression matches value1
        break;
    case value2:
        //code to execute if expression matches value2
        break;
    case value3:
        //code to execute if expression matches value3
        break;
    default:
        //code to execute if none of the cases match
}


Here's an example of how to use the switch statement in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$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;
    default:
        echo "Today is not a weekday";
}


In this example, if the variable $day is "Monday", the code in the first case will be executed, which will output "Today is Monday". If $day is "Tuesday", the code in the second case will be executed, which will output "Today is Tuesday". If $day is "Wednesday", the code in the third case will be executed, which will output "Today is Wednesday". If $day is anything else, the code in the default case will be executed, which will output "Today is not a weekday".

by darrion.kuhn , 4 months ago

@shyann 

The switch statement starts with the keyword "switch" followed by the expression you want to evaluate. This expression can be a variable or a value.


Inside the switch statement, you define different cases using the keyword "case" followed by a value that you want to check against the expression. If the expression matches the value in a case, the code inside that case will be executed.


After each case, you use the keyword "break" to tell PHP to exit the switch statement once the code in a case is executed. This prevents the code from falling through to the next case.


If none of the cases match the expression, you can define a default case using the keyword "default". The code inside the default case will be executed when none of the cases match.


Note that the break statement is essential in each case to prevent fall-through. Without a break, PHP will continue executing the code in cases below the matched case until it reaches a break or the end of the switch statement.


You can have multiple lines of code inside each case, and you can also use other PHP statements, conditions, or loops within each case.


Overall, the switch statement in PHP is handy when you have multiple conditions to evaluate and perform different actions based on those conditions.