The switch statement is used to perform different actions based on different conditions. In this article, we will see how to use the switch case statement in PHP. The switch statement is useful to perform different actions based on various conditions.
Read Also: PHP If Else Statement
Index
The switch statement is like if else if statement. It executes one block of code from many, based on the given conditions.
Syntax
switch(expression){ case value1: //code to be executed break; case value2: //code to be executed break; ...... default: //Executes if all cases are not matched; }
Example 1
<?php $favfruit = "Apple"; switch($favfruit){ case "Apple": echo "Your favorite fruit is Apple!"; break; case "Mango": echo "Your favorite fruit is Mango!"; break; case "Grapes": echo "Your favorite fruit is Grapes!"; break; default: echo "Your favorite fruit is neither Apple, Mango, nor Grapes!"; } ?>
Output
Your favorite fruit is Apple
Syntax
jump-statement; continue;
Example
<?php for($i = 1; $i < 10; $i++){ if($i % 2 == 0){ continue; } echo $i . " "; } ?>
Output
1 3 5 7 9
Read More: PHP Loops
When we need to run different blocks of code based on different conditions, the PHP switch statement comes into the picture.
You can refer to our previous blog on if..else..elseif statements to understand the differences between switch cases and the other conditional statements. We have also posted other blogs on the other basic concepts of PHP. Stay motivated and Happy Learning!
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…