-2

Please help.

for($i=0; $i<12; $i++ ){
        switch($i) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
                echo ("i is less than 5 <br>");
                break;
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
                echo ("i is less than 10 <br>");
                break;
            default:
                echo ("i is 10 or more <br>");
        }
    }

This is the example code I got in my Java book and I translated the code above to PHP.

The output of the following code:

i is less than 5 
i is less than 5 
i is less than 5 
i is less than 5 
i is less than 5 
i is less than 10 
i is less than 10 
i is less than 10 
i is less than 10 
i is less than 10 
i is 10 or more 
i is 10 or more

My question is that how come that case 0 to case 3 outputs "i is less than 5" even though it doesn't have any following code and case 4 is the one with echo statement? I'm confused, can someone explain this to me. Thanks in advance.

Helen Andrew
  • 87
  • 1
  • 2
  • 12
  • 1
    That's what "fall through" refers to - if you don't have a `break;` after a case statement, it falls through to the next one. – iainn Jul 06 '16 at 11:47
  • 1
    Your title seems to indicate you already know the answer. Furthermore, this is well covered in [the manual](http://php.net/manual/en/control-structures.switch.php) which should have been the first place you went to research this. – John Conde Jul 06 '16 at 11:47
  • but how come does case 0 to case 3 outputs i is less than 5 even though it don't have an echo statement. I have made my research about this that if a case don't have any break statements it will continue to go through the next until it encounters a break statement. I think that it should only output it i is less than 5 once when it encounters case 4 – Helen Andrew Jul 06 '16 at 12:07

2 Answers2

1

That's how the switch is supposed to operate. In order to stop falling through to the next case you have to use the break keyword. It's the same in every language I know, including JavaScript, PHP and Python.

For reference, check out the PHP manual.

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
1

Just imagine your switch like this

switch($i) {
            case 0:
               case 1:
                   case 2:
                       case 3:
                          case 4:
                             echo ("i is less than 5 <br>");
                             break;
            case 5:
               case 6:
                 case 7:
                    case 8:
                       case 9:
                         echo ("i is less than 10 <br>");
                         break;
            default:
                echo ("i is 10 or more <br>");

It will keep carrying along the chain until break is called.