views:

46

answers:

4

I'm using an array to store the names of other arrays which are dynamically generated elsewhere. I need to loop through the "names" array and access the contents of the "named" arrays. Something like this:

$names = array("one", "two", "three");
$one = array("a", "b", "c");
$two = array("c", "d", "e");
$three = array("f", "g", "h");
foreach ($process_array in $names) {
// how to access the contents of $one, $two and $three using only $names??
}

I'm preety sure I ought to be able to utilize variable variables somehow but all of the examples I've read show the logical inverse of what I'm trying to do (unless I'm misunderstanding the basic principles - entirely possible!)

Many thanks for any and all advice.

+3  A: 
$names = array("one", "two", "three");
$one = array("a", "b", "c");
$two = array("c", "d", "e");
$three = array("f", "g", "h");
foreach ($names as $name) {
// how to access the contents of $one, $two and $three using only $names??
print_r(${$name});
}
Luis Melgratti
Seems like I was thinking about this far too hard and the answer was staring me in the face. All answers correct, thanks y'all!
+1  A: 

PHP has a feature called variable variables:

foreach ($names as $name) {
    $$name;
}

For just variables you can use the syntax above ($$name). When you want to use an expression to name the variables, use the bracket syntax like ${"foo".$name}.

Gumbo
+1  A: 

Like this?

foreach ($names as $name) {
    var_dump($$name); // do something else
}
Daniel Egeberg
A: 
$names = array("one", "two", "three");
$one = array("a", "b", "c");
$two = array("c", "d", "e");
$three = array("f", "g", "h");

foreach ($names as $name) {
  foreach ($$name as $value) {
    // $value contains the array values.
  }
}

To notice it's foreach ($array as $value), not foreach ($value in $array).

kiamlaluno