Jhonny Jr.
Jhonny Jr.

Reputation: 306

PHP Cannot display content variable inside foreach loop when combine two different variable array

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?

Upvotes: 0

Views: 469

Answers (4)

codehitman
codehitman

Reputation: 1188

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

${'variables'.$b}

look at this post for more info.

Upvotes: 1

Machavity
Machavity

Reputation: 31614

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;

}

Upvotes: 1

Dilvish5
Dilvish5

Reputation: 310

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

foreach(eval('$variable_'.$b) as $k=>$v)...

Upvotes: 1

jh314
jh314

Reputation: 27802

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.

Upvotes: 1

Related Questions