Home  >  Article  >  Backend Development  >  Basic use and extended use of php switch statement

Basic use and extended use of php switch statement

伊谢尔伦
伊谢尔伦Original
2017-06-23 10:15:081381browse

A

switch statement is similar to a series of if statements with the same expression. In many cases, it is necessary to compare the same variable (or expression) with many different values, and execute different codes depending on which value it is equal to. This is exactly what the switch statement is for.

Format of switch() statement

switch(表达式){ 
case 匹配1: 
当匹配1和表达式匹配成功执行的代码; 
break; 
case 匹配2: 
当匹配2和表达式匹配成功执行的代码; 
break; 
default: 
如果case语句没有与表达式成功所执行的代码; 
}

It is very important to understand how switch is executed. The switch statements are executed line by line (actually statement by statement). Initially no code is executed. Only when the value in a case statement matches the value of the switch expression will PHP start executing the statement until the end of the switch block or until the first break statement is encountered. If you do not write break at the end of the statement segment of the case, PHP will continue to execute the statement segment in the next case.

Working principle:
Perform a calculation on the expression (usually a variable)
Compare the value of the expression with the value of the case in the structure
If there is a match, then Execute the code associated with the case
After the code is executed, the break statement prevents the code from jumping to the next case to continue execution
If no case is true, the default statement is used

Example:

The statement in one case can also be empty. This only transfers control to the statement in the next case until the statement block of the next case is not empty. This achieves multiple value matching and agreement code blocks. :
Output the same statement when the value of $i is 1 or 2 or 3:

The above is the detailed content of Basic use and extended use of php switch statement. 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