In this tutorial we will learn about the How to use PHP Switch Case Statements. PHP Switch Case Statements are the alternatives of PHP else if statement and can be used in place of PHP else/if. PHP switch statement is used to execute one of many blocks of code. The switch statement is similar to a series of IF statements on the same condition.

How to use PHP Switch Case Statements

Syntax:

switch (n) {
case n1:
code to be executed if n=n1;
break;
case n2:
code to be executed if n=n2;
break;
case n3:
code to be executed if n=n3;
break;

default:
code to be executed if n is different from all n1…n3;
}

 


Example

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}

 

Output:

 

i equals 0

 


 

Example #2 switch statements allows usage of strings

<?php switch ($i) { case "apple": echo "i is apple"; break; case "bar": echo "i is bar"; break; case "cake": echo "i is cake"; break; } ?>

 

In this PHP Tutorial we learnt about the PHP Switch case statements. In next tutorial we will learn about PHP Loops.

Pin It on Pinterest

Shares
Share This