Can it be used for looping inside the switch?

I am trying to do something like the following:

 switch ($p) {
    foreach ($modules as $m) {
    case '"'.$mod.'"':
    include 'modules/'.$m.'/cases.php';
    break;
    }
 }

      

but can't get it to work. Can a for loop be used this way inside a switch?

+2


source to share


6 answers


I don't think it is ...

Basic and shorter solution:

foreach($modules AS $m) {
    if($p == $m) {
        include 'modules/'.$m.'/cases.php';
        break;
    }
}

      



but best of all:

if(in_array($p, $modules))
    include 'modules/'.$p.'/cases.php';

      

+6


source


Yes and no

You need to move foreach outside switch

or inside the selector case

. I'm not sure why the switch () is even needed. Why not just do something for each module without running it through the switch?



And most languages ​​don't let you jump into inner blocks. Even when they do it, it's not a good practice.

+1


source


Looks like some form of Duff device - but I don't think it's legal anywhere outside C.

+1


source


If you want to do something like determining if $ p is in $ modules, and if so, include it, there is probably a better way to do this than a switch statement.

0


source


You can of course use a loop inside the switch. However, you cannot do what you are trying to do there; it just doesn't work. And I don't see any point in that. Why not just have an array of module names as keys and then do

if ($modules[$p]) {
  include $modules[$p];
} else {
  // not found...
}

      

or something like that?

0


source


I don't think you can do such a thing: right away a switch statement, the only thing you can use is the case

or statement default

.

This is what you get, tells you: btw:

Parse error: syntax error, unexpected T_FOREACH, expecting T_CASE or T_DEFAULT or '}'

      

If you want a loop and swith, you have to either put the loop "arround" the entire switch statement, or "inside" a case case.

0


source







All Articles