PHP SwitchStatement


The switch statement is used to perform different actions based on multiple different conditions.


PHP Switch Statement

If you want toselectively execute one of several code blocks, please use the switch statement.

Syntax

<?php switch (expression) { case value1: //Code block 1 break; case value2: //Code block 2 break; //More case statements default: //If there is no matching value } ?>

Parameter description:

  • expressionis the expression to be compared.
  • case value:is a possible value. Ifexpressionvalue equals a certaincasevalue, then execute the corresponding code block.
  • break;Used to terminateswitchstatement, to prevent continuing to execute the nextcase。
  • default:is optional, used to specify when there is no matchingcasethe code block to execute.

How it works:First, a simple expressionn(usually a variable) is evaluated once. The value of the expression is compared with the value of each case in the structure. If a match is found, the code associated with the case is executed. After the code is executed, usebreakto prevent the code from jumping into the next case and continuing execution.defaultThe statement is used to execute when there is no match (i.e., no case is true).

Examples

<?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 not red, blue, or green!"; } ?>

Run example »
Other Extensions