Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

4 Answers 4

up vote 1 down vote accepted

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.

share|improve this answer
    
Thanks it works... ;) –  Jhonny Jr. Aug 13 '14 at 19:10

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

foreach(eval('$variable_'.$b) as $k=>$v)...
share|improve this answer

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;

}
share|improve this answer

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

${'variables'.$b}

look at this post for more info.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.