PHP switch Statement

Back to ACP page

Table of Contents

PHP 1 switch Statement

<h4>switch Statement</h4> <p>From w3schools.com, Experiment by Teeratus_R </p> <?php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } ?>

Example 1

Result View Example

PHP 2 break Keyword

When PHP reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code, and no more cases are tested.

The last block does not need a break, the block breaks (ends) there anyway.

<h4>break_Keyword</h4> <p>From w3schools.com, Experiment by Teeratus_R </p> <?php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } ?>

Example 2

Result View Example

PHP 3 default Keyword

The default keyword specifies the code to run if there is no case match:

<h4>default Keyword</h4> <?php $d = 4; switch ($d) { case 6: echo "Today is Saturday"; break; case 0: echo "Today is Sunday"; break; default: echo "Looking forward to the Weekend"; } ?>

Example 3

Result View Example

Putting the default block elsewhere than at the end of the switch block is allowed, but not recommended.

<h4>default_Keyword_not_recommended</h4> <?php $d = 4; switch ($d) { default: echo "Looking forward to the Weekend"; break; case 6: echo "Today is Saturday"; break; case 0: echo "Today is Sunday"; } ?>

Example 4

Result View Example

PHP 5 Common Code Blocks

If you want multiple cases to use the same code block, you can specify the cases like this:

<h4>Common_Code_Blocks</h4> <?php $d = 3; switch ($d) { case 1: case 2: case 3: case 4: case 5: echo "The week feels so long!"; break; case 6: case 0: echo "Weekends are the best!"; break; default: echo "Something went wrong"; } ?>

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference