views:

506

answers:

6

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?

A: 

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.

Amber
+4  A: 

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';
janoliver
if (in_array($p, $modules)) include "modules/$p/cases.php";is shorter.
Salaryman
Just what I was looking for, thank you.
Deca
A: 

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?

hobbs
A: 

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.

Pascal MARTIN
A: 

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.

DigitalRoss
I'm actually trying to dynamically include a set of cases based on the section (module) being viewed, hence the switch. I need to include the cases for only one module at a time, where $p is the module.
Deca
A: 

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

Michael Borgwardt