PHP Switch Statement
PHP Switch Statement
The PHP switch statement is used to perform different actions based on different conditions. It is a convenient way to simplify multiple if-else statements when dealing with multiple possible values for a variable.
Multiple if-else statements can be used, but code gets confusing, and is not often the best choice. The switch statement is like an enhanced if-else if-else statement is less confusing and easy to use.
Syntax
The syntax of a switch statement in PHP is as follows:
switch (expression) {
case value1:
// code to be executed if the expression is equal to value1
break;
case value2:
// code to be executed if the expression is equal to value2
break;
// additional cases as needed
default:
// code to be executed if the expression does not match any case
}
The switch statement begins with the keyword “switch”, and round brackets that contain an expression or value.
This expression/value is matched against the value following each “case” (and if there is a match, it executes the code contained inside that case.
The break statement indicates the end of that particular case. If we omit break, it will continue executing the statements in each of the following cases.
If no match is found, it executes the default statement.
Example
Let’s understand the concept with an example to help you understand how the switch statement works.
$day = “Monday”;
switch ($day) {
case “Monday”:
echo “It’s the start of the week.”;
break;
case “Tuesday”:
echo “It’s not Monday anymore.”;
break;
case “Wednesday”:
case “Thursday”:
echo “We’re halfway through the week.”;
break;
case “Friday”:
echo “It’s almost the weekend!”;
break;
default:
echo “Enjoy your weekend!”;
}
In this example, the variable $day is compared to different values within the switch statement. Once a match is found, the corresponding code is executed, and the `break` keyword is used to exit the switch statement. If no match is found, the code within the `default` block is executed.
The switch statement is an efficient way to handle multiple conditions. The switch statement can be a alternative to using multiple if-else statements when you have a variable that can have different values. It helps to make your code more readable and easier to maintain.