Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17586

Why is all case statements execute in a switch case after a matching condition ,when not using break; in PHP

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 .

Upvotes: 0

Views: 1626

Answers (3)

iobleed
iobleed

Reputation: 91

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.

Upvotes: 0

Thulur
Thulur

Reputation: 358

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;
}
?>

Upvotes: 1

user1932079
user1932079

Reputation:

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

Upvotes: 1

Related Questions