PHP switch statements

PHP switch Statements
  • PHP switch statement is used to execute one condition from multiple condition.
  • syntax
  • switch(expression){
    case label1:
    //code to be executed
    break;
    case label2:
    //code to be executed
    break;
    ......
    default:
    default code to be executed if all cases are not matched;
    }

  • example
  • <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    $month = "February";
    
    switch ($month) {
    case "January":
    echo "31 days";
    break;
    case "February":
    echo "28/29 days";
    break;
    case "March":
    echo "31 days";
    break;
    case "April":
    echo "30 days";
    break;
    case "May":
    echo "31 days";
    break;
    case "June":
    echo "30 days";
    break;
    case "July":
    echo "31 days";
    break;
    case "August":
    echo "31 days";
    break;
    case "September":
    echo "30 days";
    break;
    case "October":
    echo "31 days";
    break;
    case "November":
    echo "30 days";
    break;
    case "December":
    echo "31 days";
    break;
    default:
    echo "Invalid input!";
    }
    
    ?>
    </body>
    </html>
    


  • Each case can have a break statement, which is used to terminate the sequence of statement.
  • The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
  • PHP allows you to use number, character, string, as well as functions in switch expression.
  • You can use semicolon (;) instead of colon (:).
  • Nested switch statement example
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    $bike = "Suzuki";
    $model = "Hayabusa";
    
    switch( $bike )
    {
    case "BMW":
    
    switch( $model )
    {
    case "G 310 R":
    echo "BMW G 310 R price is Rs. 16.85 - 20.05 lakh";
    break;
    
    case "S 1000 R":
    echo "BMW S 1000 R price is Rs. 16.70 lakh.";
    break;
    
    default:
    echo "Invalid input!";
    }
    break;
    
    case "Royal Enfield":
    
    switch( $model )
    {
    case "Himalayan":
    echo "Royal Enfield Himalayan price is Rs. 1.90 - 1.94 lakh";
    break;
    
    case "Bullet 350":
    echo "Royal Enfield Himalayan price is Rs. 1.14 - ₹1.31 lakhs";
    break;
    default:
    echo "Invalid input!";
    }
    break;
    
    case "Suzuki":
    switch( $model )
    {
    case "Gixxer SF":
    echo "Suzuki Gixxer SF price is Rs. 1.01 - 1.3 lakhs";
    break;
    
    case "Hayabusa":
    echo "Suzuki hayabusa price is Rs. 13.74 Lakh";
    break;
    
    default:
    echo "Invalid input!";
    }
    break;
    
    default:
    echo "Invalid input!";
    }
    ?>
    
    </body>
    </html>