WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 switch Statement


The switch statement is used to perform different actions based on different conditions.

If you want to select one of many blocks of code to be executed, use the Switch statement.


The PHP switch Statement

Use the switch statement to avoid long blocks of if..elseif..else code..

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;
}

Example

<?php
$favcolor = "WHITE";

switch ($favcolor) {
    case "red":
        echo "Your favorite color is red!";
        break;
    case "blue":
        echo "Your favorite color is pink!";
        break;
    case "green":
        echo "Your favorite color is yellow!";
        break;
    default:
        echo "Your favorite color is neither WHITE, pink, nor yellow!";
}
?>