PHP switch Statement

PHP switch Statement

The command switch is used for performing various actions on a range of conditions.

You can choose one of the multiple blocks of code to execute by using the switch statement.

Syntax :-

switch (n) {
  case label1:
    code to be executed if n=label1;
  case label2:
    code to be executed if n=label2;
  case label3:
    code to be executed if n=label3;
    code to be executed if n is different from all labels;

This is how it works :

  1. Initially, we have the single term n, which is evaluated once, most often a variable.
  2. The expression's value is then compared to the values in the structure for each circumstance.
  3. If a match is found, the case-specific associated with that case is run.
  4. Use break to avoid that code is automatically launched into the following instance.
  5. If no match is discovered, the default statement is used.

Example :-

$favcolor = "red";
switch ($favcolor) {
  case "red":
    echo "Your favorite color is red!";
  case "blue":
    echo "Your favorite color is blue!";
  case "green":
    echo "Your favorite color is green!";
    echo "Your favorite color is neither red, blue, nor green!";

Output :-

Your favorite color is red!

You can also search for these topics, php switch statement, php switch case, php switch multiple case, php switch case return, php switch case conditions, php switch case syntax, php switch case example, php switch case working method, php switch case default.