Home  >  Article  >  Backend Development  >  What is the usage of case in php

What is the usage of case in php

藏色散人
藏色散人Original
2022-01-04 09:59:595408browse

case in php is used in the switch statement. Its usage syntax is such as "switch (n){case label1:break;case label2:break;}". This syntax realizes the expression value and the structure. The values ​​of each case are compared, and then different actions are performed based on the conditions.

What is the usage of case in php

#The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.

What is the usage of case in php?

PHP Switch Statement

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

If you want to selectively execute one of several blocks of code, use a switch statement.

Syntax

<?php
switch (n)
{
case label1:
    如果 n=label1,此处代码将执行;
    break;
case label2:
    如果 n=label2,此处代码将执行;
    break;
default:
    如果 n 既不等于 label1 也不等于 label2,此处代码将执行;
}
?>

Working principle: First perform a calculation on a simple expression n (usually a variable). Compares the value of the expression to the value of each case in the structure. If there is a match, the code associated with the case is executed. After the code is executed, use break to prevent the code from jumping to the next case to continue execution. The default statement is executed when there is no match (that is, no case is true).

Example

<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
    echo "你喜欢的颜色是红色!";
    break;
case "blue":
    echo "你喜欢的颜色是蓝色!";
    break;
case "green":
    echo "你喜欢的颜色是绿色!";
    break;
default:
    echo "你喜欢的颜色不是 红, 蓝, 或绿色!";
}
?>

Output result:

你喜欢的颜色是红色!

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the usage of case in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn