tags:

views:

56

answers:

2

In PHP you can you $var = 'title'; $$var = 'my new title'; and it works fine. But when you try to use it with array, it doesnt work and no errors are reported.

$var = 'title'; $$var['en'] = 'my english title';

$var = 'description'; $$var['en'] = 'my english description';

Thanks for the help

[EDIT] If I do $$var = array(); array_push($$var,'test'); it works and it outputs title[0] = 'test'; But I really need named index : /

+2  A: 

write it like this:

${$var}['en']

from the docs:

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Link For Reference

GSto
wow... thanks! I checked the manual but I never found this page. Thanks again!
Tsukassa
It should be ${$var}['en']
Steven Oxley
oops, you're right, I made a typo. Fixed my answer.
GSto
+1  A: 

What you really want is:

${$var}['en']

The problem, as stated in the manual, is ambiguity. When you write $$var['en'], it tries to find the value of $var['en'] first and then find a variable with the name of the value of that index. The braces in ${$var}['en'] show that you want $var to be expanded first.

Steven Oxley