PHP Switch Case Statement

In PHP, switch statement is a variant of the if-else combination and is used when we need to compare a variable against a large number of values depending on the value that is matched.

Syntax

switch (x) {
    case label1:
        //code to be executed if x=label1;
        break;
    case label2:
        //code to be executed if x=label2;
        break;
    case label3:
        //code to be executed if x=label3;
        break;
    ...
    default:
        //code to be executed if x is different from all the above labels;
}

In case of if...elseif...else statement same variable is compared again and again with different values. This looks quite cumbersome, specially when later want to change the expression used in all of the tests. For this purpose, PHP provides an easy way to run these types of tests: the switch statement.

PHP Switch Case Statement Example

<?php 
$stdcode = "001";
switch ($stdcode) {
    case "001":
        echo "std code pertains to New Delhi!";
        break;
    case "002":
        echo "std code pertains to Mumbai!";
        break;
    case "003":
        echo "std code pertains to Kolkata!";
        break;
    case "004":
        echo "std code pertains to Chennai!";
        break;	
    default:
        echo "std code does not pertain to any Metro!";
}

This will produce following result:

std code pertains to New Delhi!