Register Now

Login

Lost Password

Enter your email to reset your password.

The Switch statement is used to perform when more than one alternative choices present.

The switch statement help in avoiding long block of if..elseif..else code.

Syntax

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

How it works?

It has a single expression i.e. m (might be a variable) is evaluated once. Then the value of the expression is compared with value of each case. If value of expression (m) matches with the value of case, then associated case value is returned.

Incase a match is found, then use break to prevent the code from running into the next case.

If none of the value of expression is matched then the default case value is returned.

Let us understand with the help of example:

<?php
$favcity = "delhi";

switch ($favcity) {
    case "delhi":
        echo "Your favorite city is delhi!";
        break;
    case "bangalore":
        echo "Your favorite city is bangalore!";
        break;
    case "kolkata":
        echo "Your favorite city is kolkata!";
        break;
    default:
        echo "Your favorite city is neither delhi, bangalore, nor kolkata!";
}
?>