PHP The switch statement

The switch statement

The switch statement is similar to a series of if statements on the same expression.
In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to.
This is exactly what the switch statement is for.

Syntax:

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

This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically. Thedefault statement is used if no match is found.

Example:

<?php
$subject = "php";

switch ($subject) {
    case "c":
        echo "You have Selected C language";
        break;
    case "cpp":
        echo "You have Selected C++ language";
        break;
    case "php":
        echo "You have Selected PHP Scripting language";
        break;
    default:
        echo "You have Selected Nothing.";
}
?>

Output:

Tutorialik.com
You have Selected PHP Scripting language

Alternative Implementation of switch statement

Example:

Above example is also implemented with if else if statement as follows.

<?php
    $subject = "php";

    if ($subject == "c") {
        echo "You have Selected C language";
    } elseif ($subject == "cpp") {
        echo "You have Selected C++ language";
    } elseif ($subject == "php") {
        echo "You have Selected PHP Scripting language";
    } else {
        echo "You have Selected Nothing.";
    }
?>

Output:

Tutorialik.com
You have Selected PHP Scripting language


Share This Page to Download:

Share to Download

Share This Page on:


Ask Question