0

I'm confused in how to use $$ to use a string as a variable, mainly when it comes to use a string to refer an array index. Consider the following case:

$colors = array(
'r'=>"red",
'b'=>"blue"
);
$vr = "colors[r]"; //I tried even this "color['r']"
echo $$vr; // I tried even this ${$vr}

Can anyone tell if it is possible to do the above. expected o/p is red using "color[r]" as string and then using it as variable.

Nishant
  • 6,175
  • 1
  • 13
  • 27

1 Answers1

0

You can't do that directly. Consider the following:

$varName = array_shift(explode('[', $vr));

foreach($$varName as $key=>$value){
    echo $key.": ".$value."<br />";
}

this will print out:

r: red
b: blue

The variable variable is just the first part (colors). You can't include the key in this.

mnagel
  • 5,938
  • 4
  • 25
  • 63
Swissdude
  • 3,102
  • 3
  • 28
  • 60
  • the array can be deeper, to next level i.e. it could have been, $colors['r']['shade']. What if its the following case: $vr = "colors['r']['shade']". Its dynamic and the depth of array can be anything. – Nishant Jul 08 '13 at 04:55
  • Then you'd have to write your own parser. But before I go deeper into that: What's the goal of this all? Why are you doing what you're doing? ;) – Swissdude Jul 08 '13 at 11:25