variable contents as array names

I want to take data from an array and use the key as the name for a new array.

foreach ($row as $key => $val) {
${$key}[$val] = “chum”;
$test .= “$key - $val – $$key[$val]\n”;
}

When I print $test to see why it’s not working:

shark - 1 – $d
barracuda - 4 – $f
tuna - 3 – $e
swordfish - 3 – $s

It obviously knows what $key and $val are…why won’t it make my new array for me!!!

Hi there,

To create a variable name from a value that you get from another variable, you would use the $$ notation. Take the example below:

[php]foreach($array as $key => $value)
{
$$key = $value;
}[/php]

Think of it this way: ${$key} with $key being the value green would turn into ${green} or just $green.

Hope this helps.

Thanks, but I need to associate both key and value together with a new value, so this won’t do.

try this

[php]
foreach ($row as $key => $val) {
${$key."[".$val."]"} = “chum”;
$test .= “$key - $val – $$key[$val]\n”;
}
[/php]

or try this

[php]
foreach ($row as $key => $val) {
${$key[$val]} = “chum”;
$test .= “$key - $val – $$key[$val]\n”;
}
[/php]

or try this

[php]
foreach ($row as $key => $val) {
$$key[$val] = “chum”;
$test .= “$key - $val – $$key[$val]\n”;
}
[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service