php

PHP Switch


 

It provides a concise way to handle multiple conditions in a more readable manner than if else if statement. It provides a simple way to have a single expression whose value needs to be compared against multiple possible values.

 

Syntax:

<?php                                                                                                                    
   switch ($expression) {
       case value1:
           // Code to be executed if expression matches value1
           break;
       case value2:
           // Code to be executed if expression matches value2
           break;
       default:
           // Code to be executed if expression doesn't match any case
   }        
?>

 

Flow of Switch Statement

 

Evaluation

• The switch statement evaluates a given expression once.
• This expression is typically compared to the values specified in case labels.


Matching Labels

• After evaluating the expression, the switch statement looks for a case label whose value matches the evaluated expression.


Execution of Code Block

• If a matching label is found, the code block associated with that label is executed.
• If there is no break statement after the code block, execution may fall through to subsequent cases.


Default Case

• If none of the case labels match the evaluated expression, the default case (if specified) is executed.

 

Example:

<?php
   $no = 5;
   switch ($no)
   {
       case 1:
           echo "number 1";
           break;
       case 2:
           echo "number 2";
           break;
       case 3:
           echo "number 3";
           break;
       default:
           echo "number greater than 3";
   }        
?>

 

OUTPUT:

 

 

Note:

"If you forget to put the break statement in a case block and that case is matched, the program will not stop there. Instead, it will continue to execute the code in the next case block, even if the condition of that next case is not met."