$a=5;switch($a){ case 6: echo "\$a is 6
"; case 5: echo "\$a is 5
"; case 4: echo "\$a is 4
";}
As in the above example, my understanding is that each time $ A is compared to the value of the case, the output statement is the same, and the non-conformance is the next condition. But the output of the browser is
$a is 5
$a is 4
I don't quite understand. The last Case statement clearly $a!=4 will also output.
(My understanding of the switch statement must be preceded by a break is this: This allows you to jump out of a switch immediately after finding a qualifying case to speed up execution.) It doesn't look right now. )
Reply content:
$a=5;switch($a){ case 6: echo "\$a is 6
"; case 5: echo "\$a is 5
"; case 4: echo "\$a is 4
";}
As in the above example, my understanding is that each time $ A is compared to the value of the case, the output statement is the same, and the non-conformance is the next condition. But the output of the browser is
$a is 5
$a is 4
I don't quite understand. The last Case statement clearly $a!=4 will also output.
(My understanding of the switch statement must be preceded by a break is this: This allows you to jump out of a switch immediately after finding a qualifying case to speed up execution.) It doesn't look right now. )
You can understand that switch will jump to the first matching case to continue execution, depending on the condition.
The case is just a tag for switch jumps, and does not partition the block.
So:
- Even if more than one case matches a switch, it will only jump to the first matching case.
- If it does not break, it starts at the first case that matches and executes until the end of the entire switch structure.
Swich just jumps there to start execution, and if not break will execute all of the following case all over again.
This is the foundation! Question and answer you this problem I feel a sense of accomplishment is not ....
The principle is simple: when the value of a case is matched to $ A, the code block of the sample is executed. The reason that the break exists is that the code after the matching case is placed will be executed. if $a=6; Then 6, 5, 4 will be output
Because switch is not a pattern match , it is similar to JMP in the assembly.
The original purpose of this syntax is to satisfy semantic coherence, see the following scenario,
switch($a){ case 6: case 5: echo "\$a is not 4
"; break; case 4: echo "\$a is 4
";}
6 and 5 are treated the same way.