0

I have an multiple variable like this and i want to combine two variable in foreach loop:

$foo = array(4, 9, 2);

$variables_4 = array("c");

$variables_9 = array("b");

$variables_2 = array("a");

foreach($foo as $a=>$b) {

foreach($variables_{$b} as $k=>$v) {

echo $v;

}

}

After i run above code it display error "Message: Undefined variable: variables_"

Is anyone know how to solve this problem?

Jhonny Jr.
  • 363
  • 3
  • 4
  • 15

4 Answers4

1

You can use Variable variables to get the job done, but in this case it is kind of ugly.

A cleaner way to do this is by using nested arrays:

$foo = array(4=>array("c"),
             9=>array("b"),
             2=>array("a"));

foreach($foo as $a=>$b) {
     foreach($b as $k=>$v) {
          echo $v;
     }
}

Then you won't have to create a lot of variables like $variables_9.

jh314
  • 27,144
  • 16
  • 62
  • 82
1

You should try to use eval(), for example:

foreach(eval('$variable_'.$b) as $k=>$v)...
Dilvish5
  • 310
  • 4
  • 12
1

I would highly suggest another route (this is a poor structure). But anyways...

Try concatenating into a string and then use that

$var = 'variables_' . $b;
foreach($$var as $k=>$v) {

echo $v;

}
Machavity
  • 30,841
  • 27
  • 92
  • 100
1

This is a syntax error. You need to concatenate the strings within the brackets:

${'variables'.$b}

look at this post for more info.

Community
  • 1
  • 1
codehitman
  • 1,148
  • 11
  • 33