Follow The New Tutorial updates on WhatsApp, Telegram or YouTube.

PHP Switch Statement

switch statement is used to select one of many blocks of code to be executed.

The switch statement is used to perform different actions based on different conditions. It works like PHP if-else-if statement.

PHP allows you to use number, character, string, as well as functions in switch expression.


switch (n) {
  case label1:
    //code to be executed if n=label1;
  case label2:
    //code to be executed if n=label2;
  case label3:
    //code to be executed if n=label3;
    //code to be executed if n is different from all labels;

break is used to prevent the code from running into the next case automatically. It is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.

The default statement is used if no match is found. It is an optional statement. It 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.

PHP Switch Example

case 10:      
echo("number is equals to 10");      
case 20:      
echo("number is equal to 20");      
case 30:      
echo("number is equal to 30");      
echo("number is not equal to 10, 20 or 30");      
PHP Switch Example – Output