PHP switch Statement with simple example

By Faruque Ahamed Mollick

PHP switch statement was first introduced in PHP 5. The switch statement is used to perform different actions that based on different conditions.

Below is the syntax of a switch statement:

switch (n) {
    case value1:
        Here is the code that needs to be executed if n=value1;
        break;
    case value2:
        Here is the code that needs to be executed if n=value2;
        break;
    case value3:
        Here is the code that needs to be executed if n=value3;
        break;
    ...
    default:
        code to be executed if n is different from all values;
}

In most of the time “n” is a variable which is a single expression need to be taken first. The value of n then compared with the values for each case in the structure. If there any match found, the block of code associated with that particular case will be executed and all other cases will be ignored. Use the “break” to prevent the code from running into the next case automatically. If there are no match fond, the default statement will then execute.

An example of PHP switch statement:

Here is a simple example code:

<?php
$color = "black";

switch ($favcolor) {
    case "black":
        echo "The color is black!";
        break;
    case "yellow":
        echo "The color is yellow!";
        break;
    case "green":
        echo "The color is green!";
        break;
    default:
        echo "No color available between black, yellow and green!";
}
?>

Now run the above PHP code on a server and you will able to see the below output for the code:

The color is black!

If you change the black into any color between yellow or green then it will show the output “The color is yellow!” and “The color is green!” respectively.

In real life, the switch is one of the widely used statement in PHP that can be used in many places by replacing the usual “if else” PHP statement and make the coding simpler.

 

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *