Switch Case

0 margieoverstree December 8, 2020

When there are a number of else alternatives, a switch statement is another way of representing this multi-way selection. It allows the user to choose a statement among several alternatives.  It is used to be compared with different constants, and in case it equal to a constant, a set of statements are to be executed. The constants in the case statement may be either charor inttype only.

The syntax of the switch statement is:

switch(variabe name)
{
    case case_constant_1:
         statements;
         break;

    case case_constant_1:
         statements;
         break;

    default:
         statements;
}
Switch Statement
Switch Statement

Let’s look at one example to make clear concepts on switch case.

<?php

    $choice = 2;
    echo "You choice is $choice";

    switch($choice)
    {
        case 1:
            echo "You have chosen File menu item\n";
            break;

        case 2:
            echo "You have chosen Edit menu item\n";
            break;

        case 3:
            echo "You have chosen Save menu item\n";
            break;

        default:
            echo "Invalid Options\n";
    }

?>

The output of the above program is:

You choice is 2
You have chosen Edit menu item