Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Difference between break and continue in switch case

What is the different between

switch (variable) {
        case 'value':
        # code...
        break;

        case 'value':
        # code...
        break;
}

and this one

switch (variable) {
        case 'value':
        # code...
        continue;

        case 'value':
        # code...
        continue;
}

It's really different result or just same?

like image 369
Vinsens Avatar asked Apr 11 '26 02:04

Vinsens


2 Answers

This is a special case for PHP because, as stated by the official documentation:

Note: In PHP the switch statement is considered a looping structure for the purposes of continue. continue behaves like break (when no arguments are passed). If a switch is inside a loop, continue 2 will continue with the next iteration of the outer loop.

So in essence it means there is no actual difference between your two examples. However for clarity I think it would be best to use break as that is the standard in other languages. Note also that you could use continue 2 (or 3, 4...) to advance to the next iteration of a loop if the switch is inside a loop (or more).

like image 93
Technoh Avatar answered Apr 12 '26 14:04

Technoh


In PHP the above two codes work in same way. Here the break and continue statement prevent control going to next case. That is the continue acts just like break here. Also switch is intended to be executed only once. It's not a loop. Hence continue is not relevant here.

Note:If there is loop enclosing this switch statement then the result will be different.

like image 37
Harikrishnan Avatar answered Apr 12 '26 16:04

Harikrishnan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!