How to use the switch statement in PHP?

Member

by shyann , in category: PHP General , 7 months ago

How to use the switch statement in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 6 months 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".