views:

59

answers:

3

I'm trying to figure out why this works:

$joe = "hey joe";
$something = "joe";
print_r(${$something});

But this doesn't:

$joe["where_you_going"] = "hey joe";
$something = "joe[where_you_going]";
print_r(${$something});

Why is this? Is there a way to do what I attempted in the second example?

A: 

The variable variable syntax does not allow this.
Would it make sense in your case to do one of these things instead?

Use a variable as the array index:

$joe["where_you_going"] = "hey joe";
$something = "where_you_going";
print_r($joe[$something]);


Use a variable as the name of the array and another as the index:

$joe["where_you_going"] = "hey joe";
$something1 = "joe";
$something2 = "where_you_going";
print_r(${$something1}[$something2]);


Use eval to evaluate the whole expression:

$joe["where_you_going"] = "hey joe";
$something = '$joe["where_you_going"]';
print_r(eval("return {$something};"));
Alexandre Jasmin
+1  A: 

No, you can't do it like that.

The PHP idea of "variable variables" is usually better done as arrays anyway.

Andy Lester
+1  A: 

Variable variables is a special feature in PHP that permits your first example: http://php.net/manual/en/language.variables.variable.php. It is not an eval which is why it does not work in the second example.

In the second example joe[where_you_going] there's the name of an array, the bracket operator and the name of the index. You can't combine just combine all three since they require operations (indexing into an array) and not just naming. You could do:

$joe["where_you_going"] = "hey joe";
$something = "joe";
$something_else = "where_you_going";
print_r(${$something}[$something_else]);
jcmoney