PHP Switch

PHP switch control statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

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

  1. The default is an optional statement. The default statement must always be the last statement.
  2. There can be only one default in a switch statement. More than one default may lead to a Fatal error.
  3. Each case can have a break statement, which is used to terminate the sequence of statement.
  4. The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
  5. PHP allows you to use number, character, string, as well as functions in switch expression.
  6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
  7. You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP Switch Example

<?php      
        $month=2;      
        switch($month){      
            case 1:      
                echo("1st Month is January");      
                break;      
            case 20:      
                echo("2nd Month is February");      
                break;      
            case 30:      
                echo("3rd Month is March");      
                break;      
            default:      
                echo("Sorry, Month details is not available!");      
        }     
    ?> 
Output: 2nd Month is February
 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

60425