Tuesday, August 15, 2017

PHP Switch Statement



PHP switch statement is used to execute one statement from multiple conditions. It is similar to If, If-Else, Else-If Statements but the way of evaluating the condition is different.

Or succinctly,
Switch statement can compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to.


Syntax:
switch(expression){      
case value1:      
 //code to be executed  
 break;  
case value2:      
 //code to be executed  
 break;  
case value3:      
 //code to be executed  
 break;
......      
default:       
 // code to be executed if all cases are not matched with condition/expression  
}

Example :
<?php
$i = 2; //set the variable to 2
switch ($i) {
    case 0:
        echo "i equals 0";
        break;    
    case 1:
        echo "i equals 1";
        break;    
    case 2:
        echo "i equals 2";
        break;  
    default:    
        echo("No match found for variable i");    
}       

?>

Output:
--------------
i equals 2



No comments:

Post a Comment