📜  php switch case - PHP (1)

📅  最后修改于: 2023-12-03 15:18:21.279000             🧑  作者: Mango

PHP switch case

The PHP switch case statement is a control structure that allows you to execute different blocks of code depending on the value of a variable or an expression. It provides an alternative to writing multiple if-else statements, making your code more concise and readable.

Syntax

The basic syntax of the switch case statement is as follows:

switch (variable_expression) {
  case value1:
    // code to be executed if variable_expression matches value1
    break;
  case value2:
    // code to be executed if variable_expression matches value2
    break;
  // ... more cases
  default:
    // code to be executed if variable_expression doesn't match any case
}
  • variable_expression: The value or expression to be tested against each case.
  • case value: The value to be matched against variable_expression.
  • break;: The statement that terminates the current case and transfers control to the next statement outside the switch block.
  • default: The optional case that is executed if variable_expression doesn't match any of the cases.
Example

Let's look at an example:

$grade = "A";

switch ($grade) {
  case "A":
    echo "Excellent!";
    break;
  case "B":
    echo "Good!";
    break;
  case "C":
    echo "Fair!";
    break;
  default:
    echo "Fail!";
}

In this example, the variable $grade is compared to each case using the == operator. If the value of $grade matches a case, the corresponding code block is executed. If none of the cases match, the code in the default case is executed.

Tips

Here are some tips for using the switch case statement in PHP:

  • You can use multiple case statements for the same code block by omitting the break statement in each case. This allows you to specify multiple values that should execute the same code. For example:
switch ($day) {
  case "Monday":
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
  case "Friday":
    echo "Weekday";
    break;
  case "Saturday":
  case "Sunday":
    echo "Weekend";
    break;
}
  • You can also use expressions in cases, such as variables or function calls. For example:
switch (true) {
  case ($x > $y):
    // code here if x is greater than y
    break;
  case ($x < $y):
    // code here if x is less than y
    break;
  default:
    // code here if x equals y
}
  • Always include the break statement at the end of each case to avoid executing the code in the following cases.

  • Be careful when using the switch case statement with floating-point numbers, as their values may not be exact due to rounding errors.

Conclusion

The PHP switch case statement provides a flexible way to execute different code blocks based on the value of a variable or an expression. Use it to simplify your code and avoid repetition.