Is it possible to use for loop inside a switch?

前提是你 提交于 2020-01-23 09:44:11

问题


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?


回答1:


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';



回答2:


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.




回答3:


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




回答4:


If you're wanting to do something like determine if $p is in $modules, and if so, include it, there's probably a better way to do that than a switch statement.




回答5:


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?




回答6:


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.



来源:https://stackoverflow.com/questions/1391211/is-it-possible-to-use-for-loop-inside-a-switch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!