Switch Case,无法理解

Switch Case,无法理解

问题描述:

I am trying to learn switch case php code. Here is the program that is working fine when using break.

for ($i=1;$i<=100;$i++) {
switch(true) {
        case ( $i%5 == 0  && $i%3 == 0 ):
            print 'foobar';
            break;
        case ( $i%3 == 0  ):
            print 'foo';
            break;
        case ( $i%5 == 0 ):
            print 'bar';
            break;
        case ( $i%5 != 0  && $i%3 != 0 ):
            print $i;
            break;
    } 
    echo '<br>';
}

But when I use the following code, it is giving me unexpected results:

for ($i=1;$i<100;$i++) {
switch(true) {
    case ( $i%3 == 0  ):
        print 'foo';
    case ( $i%5 == 0 ):
        print 'bar';
    default:
        print $i;
}
echo '<br>';
}

What is wrong in the second example?? Will default executes even when any above case is executed?? Also why $i%5 case is running for when $i equals to 3??

Because the first one uses break, and the second snippet doesn't.

If you don't add break, the code from the next case will also be executed, even if that condition isn't met.

That is just how switch works in PHP, and in a couple of other C-like languages as well. It differs from the (similar) case statement as you may know it from Pascal-like languages and SQL.

In a PHP switch() statement, once a case has been met, every following line of code will be executed until either a break or the end of the block.

This allows for the intentional use of what's called a "fall through"

That is why your first example works and your second example did not do as you expected.