Why Does The Switch Statement Execute A Case Block Even When A Match Is Not Found?
Solution 1:
From the manual:
The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.
switch(1){
case 1:
echo 1; // echos 1 (as expected)
break; // stop!!!
case 2:
echo 2; // won't get here
break;
case 3:
echo 3; //or here
break;
}
Solution 2:
The reason it's that way is probably because PHP borrowed the syntax from C.
However the reason it was originally this way is it helps to reduce code duplication I suspect.
If you have an if like:
if($item == 'SOUP' || $item == 'FRIES'){
eat($item);
}elseif($item == 'JUICE'){
drink($item);
}else{
use($item);
}
If switches never followed through you would need 4 cases with 'SOUP' and 'FRIES' having the same logic, without this you can make the switch nicer:
switch($item){
case 'SOUP':
case 'FRIES':
eat($item);
break;
case 'JUICE':
drink($item);
break;
default:
use($item);
break;
}
Solution 3:
I know that PHP continues to check the switch statement cases if you don't use break after each case
Seems like you didn't understand. You missed to use the break
keyword:
switch(1){
case 1: echo 1; break;
case 2: echo 2; break;
case 3: echo 3; break;
}
Note that a case
statement is like an entry point in the code. After a case condition matches the code will run through all cases until the break
is reached.
To your update: Note that this behaviour is the same for PHP as for most programming languages including : C, C++, Java, Javascript, ActionScript, Pascal, ....
Solution 4:
Why does the switch statement execute a case block even when a match is not found?
If you do not use break
, it will execute all the switches, which can be helpful sometimes. for example:
switch ( count ) {
default : puts ( " ++++.....+++ " ) ;
case 4: puts ( " ++++ " ) ;
case 3: puts ( " +++ " ) ;
case 2: puts ( " ++ " ) ;
case 1: puts ( " + " ) ;
case 0:;
}
So if count is 3 you get output:
+++
++
+
If 2, you get output
++
+
if 10, you get:
++++.....+++
++++
+++
++
+
So there are times when you want your switch to execute the other cases, once it finds what you want. Like the code above.
You could do this with else if, but it would be a lot more typing.
Post a Comment for "Why Does The Switch Statement Execute A Case Block Even When A Match Is Not Found?"