-2

I have a switch in the form of:

switch ($action) {
case 'saveTemp':
break;
case 'save':
break
}

I want to be able to have a condition on the break like so:

switch ($action) {
case 'saveTemp':
    if ($skipbreak) {
        break;
    }
case 'save':
break
}

In simple terms, when $skipbreak == true I want the code to fall through the saveTemp case to the save case.

Is it possible?

Thanks.

3 Answers3

2

Most probably you won't do what I'm going to tell you. At least not for a while, then later when you revisit this question of yours (by chance) you'll realized that my answer was right.

Don't nest if blocks inside switch blocks, don't even nest switch blocks inside switch blocks. Both are a code smell, a sign that your code is violating the SRP (single responsibility principle). Which means that this particular part of your code is in charge of too many different things at once.

Go up one level or maybe more than one level in your code hierarchy and find places where you can deletegate certain tasks to specific functions. Maybe you realize that you need to encapsulate a group of functions within a class. All of a sudden, you realize that you don't need nested control blocks anymore.

If you use PHPLOC or similar metric tools you will also realize that the cyclomatic complexity of your code goes down as you refactor it as suggested and you will probably see a performance improvement as well.

markus
  • 40,136
  • 23
  • 97
  • 142
1

yes it is possible and you just did it. however it doesn't really make sense that you'd want to do that. oh yea and like nickb said you need to negate your skip logic like so:

if(!$skipBreak)
    break;

You should consider using an if-else block instead of a switch statement. see When to use If-else if-else over switch statments and vice versa

Community
  • 1
  • 1
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
0

you can also nest a switch case within a switch case as follows:

$action = 'saveTemp'; // Example using saveTemp
$skipbreak = TRUE;    // Example using TRUE

switch ($action) {
    case 'saveTemp':
    switch ($skipbreak) {
        case TRUE:
        echo 'this is True';
        break;
        case FALSE:
        echo 'this is FALSE';
        break;
    }
    break;
    case 'save':
    echo 'this is save';
    break;
}
fizzy drink
  • 682
  • 8
  • 21