简体   繁体   中英

Is it possible to use for loop inside a switch?

I'm attempting 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. Is it possible to use a for loop in this manner, inside a switch?

I don't think it is...

Basic and shorter solution:

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

but the best would be:

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

Yes and No

You need to move the foreach outside the switch or inside the case selector. I'm not sure why the switch() is even necessary. Why not just do whatever to each module without running it through a switch?

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

看起来像Duff的某种形式的设备 -但我认为C之外的任何地方都不合法。

如果您想执行类似的操作,例如确定$ p是否在$ modules中,如果包含,则包括它,这可能是比switch语句更好的方法。

You certainly can use a loop inside a switch. You can't, however, do what you're trying to do there; it just doesn't work. And I don't see any point to it either. Why not just have an array with the module names as keys, and then do

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

or something to that effect?

I don't think you can do such a thing : immediatly a switch statement, the only thing you can use is a case or a default statement.

That is what the error you are getting is telling you, btw :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM