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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

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;

}

Comments

1

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

${'variables'.$b}

look at this post for more info.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.