Home >Backend Development >PHP Tutorial >PHP control statement Switch_PHP tutorial
Switch Statement
Use the Switch statement if you want to selectively execute one of several blocks of code.
Use Switch statements to avoid lengthy if..elseif..else blocks.
Syntax
switch (expression){case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break;default: code to be executed if expression is different from both label1 and label2;} |
Examples
How it works:
pairs expressions (usually Variable) performs a calculation
Compares the value of the expression with the value of the case in the structure
If there is a match, execute the code associated with the case
After the code is executed , the break statement prevents the code from jumping into the next case to continue execution
If no case is true, use the default statement
<?phpswitch ($x){case 1: echo "Number 1"; break;case 2: echo "Number 2"; break;case 3: echo "Number 3"; break;default: echo "No number between 1 and 3";}?> |