PHP - Switch Statement

Switch statement uses to perform different actions based on the different conditions of same variable at once. It takes one variable as an input and then check different conditions setup for switch statement. It acts like a set of if statements define for a variable.

Syntax:
switch (<variable>){
    case <label 1>:
        {code to be executed if the variable is label 1};
        break;
    case <label 2>:
        {code to be executed if the variable is label 2};
        break;
   default:
        {code to be executed if the variable is not equal to above labels};
        break;
}


Ex:
<?php
    $num = 5;
    switch ($num){
        case 1:
            echo "One";
            break;
        case 2:
            echo "Two";
            break;
        case 3:
            echo "Three";
            break;
        case 4:
            echo "Four";
            break;
        case 5:
            echo "Five";
            break;
        default:
              echo "Not in the range";
              break;
        }
        ?>

Out put

No comments:

Post a Comment