0

Hi i can understand what is going on here , but want to know the purpose ,

in this switch case statement

<?php
switch(1) {
case 1: print("Book Details<br />");
case 2: print("Book Author<br />");
default: print("Missing Book<br />");
}
?> 

the result is

Book Details
Book Author
Missing Book

my expected result was

Book Details
Missing Book

My question is that

*in switch statement we are checking switch(1) , so how is it possible to execute case 2: default should print and i can understand that . is there any particular reason to this ?

please explain , thanks in advance .

2
  • You may want to remove the codeigniter tag as this question doesn't relate to that specifically.
    – user1932079
    Commented Jul 6, 2014 at 8:27
  • 1
    @Jeremy Miller did that :) Commented Jul 6, 2014 at 8:27

3 Answers 3

1

Read the documentation paragraph after Example #2

It is important to understand how the switch statement is executed in order to avoid mistakes. 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.

3 examples then follow showing the effect of break and the role of default

1

Like you mentioned in the question it depends on the break statement. The reason is maybe someone wants to have 2 or more cases with the same result and another one with a different.

Something like:

<?php
switch($aVar) {
case 1:
case 2: print("Both cases show this sentence");
        break;
case 3: print("This case shows a different one.");
        break;
default:
        print("No matching case");
        break;
}
?>
0

This is knows as fall through. Due to the absence of break statement, PHP continues to execute the statements until the end of the switch block. Therefore you should use switch case in following format:

switch (n) {
 case label1:
   code to be executed if n=label1;
   break;
  case label2:
    code to be executed if n=label2;
    break;
 case label3:
    code to be executed if n=label3;
    break;
 default:
    code to be executed if n is different from all labels; 
} 

Use break to prevent the code from running into the next case automatically.

Not the answer you're looking for? Browse other questions tagged or ask your own question.