PHP switch Statement
This statement is used to perform different actions based on different conditions
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
To prevent the code from running into the next case automatically use break.
Important points to be noticed about switch case:
- The default is an optional statement. Even it is not important, that default must always be the last statement.
- There can be only one default in a switch statement. More than one default may lead to a Fatal error.
- Each case can have a break statement, which is used to terminate the sequence of statement.
- The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
- PHP allows you to use number, character, string, as well as functions in switch expression.
- Nesting of switch statements is allowed, but it makes the program more complex and less readable.
- You can use semicolon (;) instead of colon (:). It will not generate any error.