In the previous tutorial we have discussed about php if..else..elseif statements. This tutorial we are going to discuss above PHP swith. The PHP switch statement is one of the most important conditional statements.

PHP switch Statement :

The PHP switch statement is used to initiate certain actions based on various conditions.

It is used to pick a block of statements among many, based on certain conditions.

Syntax :


switch (n) {
case 1:
code to be executed if n=1;
break;
case 2:
code to be executed if n=2;
break;
case 3:
code to be executed if n=3;
break;
...
default:
code to be executed if n is different from all cases;
}

The process of execution follows the following trend.

The first variable is evaluated. This value is compared against other values in each structure. If a match is found, the block of code that is associated with the match is executed.

The key word break should be used to prevent automatic proceeding of execution onto the next case. Absence of a match returns the default statement.

PHP switch Case Example :


<?php

$buy = "Audi";

switch ($buy) {
case "McLaren":
echo "McLaren is one of the most expensive vehicles";
break;
case "Audi":
echo "Audi is a popular car";
break;
case "Mercedes":
echo "Mercedes is one of the most stable vehicles";
break;
default:
echo "Unfortunately your favorite pick is out of stock :-(";
}
?>

Output:

Audi is a popular car

Let us test for the absence of a match. We shall select a car that is not found on the list. Let us take a Maybach.


<?php

$buy = "Maybach";

switch ($buy) {
case "McLaren":
echo "McLaren is one of the most expensive vehicles";
break;
case "Audi":
echo "Audi is a popular car";
break;
case "Mercedes":
echo "Mercedes is one of the most stable vehicles";
break;
default:
echo "Unfortunately your favorite pick is out of stock :-(";
}
?>

Output:

Unfortunately your favorite pick is out of stock :-(

Switch statements are very useful as they can be applied in many applications. It may be used in the case of a school grading system or in selection of certain colors or vehicles. It is up to the developer’s creativity.

Happy Learning:)