The following code shows an Example of switch case statement in PHP.

Like other programming languages, PHP also offers switch case statement. When we develop a software application, whether a larger one or a smaller one we need to deal with situation that encounter as an outcome of certain conditions. Nearly all programs use conditional statements. Similarly, language compilers also provide if and if..else statements.

However, when the program’s outcome depends on the evaluation of many conditions that we need to check, we require either nested if statements or an if…else ladder. So, the use of many if statements make error prone and hard to debug. For this purpose, the programming languages also provide a switch case statement.

Basically, a switch case statement evaluates an expression. Further, it compares the value of expression with one or more case labels depending on whether a match is found or not. At first, the switch case statement compares the value of expression with the first case label. In case, both values match, the statements following that case label execute. The presence of break statement indicates that when the execution of that set of statements is over, the control comes out of the switch case statement.

In case, the match is not found with the first case label, the next case label is considered. This process repeats till any one of the following occurs: a matching case label is found, default keyword is encountered, or the end of switch statement arrives.

The following code is a simple example of using switch case statement in PHP. Here we specify $myblog as the expression in switch statement. Furthermore, the variable $myblog can take its value using an HTML form through GET or POST variable.

<?php
 $myblog='programmingempire.com';
 switch($myblog)
 {
   case 'programmingempire.com': $rank=1;
                                 break;
   case 'anotherblog.com': $rank=2;
                                 break;
   case 'agoodblog.com': $rank=3;
                                 break;
   case 'newblog.com': $rank=4;
                                 break;
   default: $rank=0;
            echo 'Unknown Blog!';
            break;     
 }
 echo '<h1>The ranking of ', $myblog, ' is ', $rank,'</h1>';
?>

Output

Using switch case statement in PHP
Using switch case statement in PHP

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

programmingempire