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

Basic use and extended use of php switch statement

伊谢尔伦
Release: 2023-03-11 07:52:02
Original
1543 people have browsed it

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语句没有与表达式成功所执行的代码; 
}
Copy after login

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:

<?php 
switch ($x) 
{ 
case 1: 
echo "Number 1"; 
break; 
case 2: 
echo "Number 2"; 
break; 
case 3: 
echo "Number 3"; 
break; 
default: 
echo "No number between 1 and 3"; 
} 
?>
Copy after login

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:

<?php 
switch($i){ 
case 1: 
case 2: 
case 3: 
echo "$i的值为$i的值为1或2或3"; 
break; 
} 
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template