inactive Posted April 7, 2008 Share Posted April 7, 2008 hey guys, i know you can do the following: <?php $var_name = 'foo'; $$var_name = 'bar'; echo $foo; ?> which prints "bar" (correctly), but i would like to do something similar with an array instead, so... <?php $var_name = 'foo'; $$var_name[1] = 'bar'; print_r($foo); ?> which i would like to return Array ( [1] => bar ), but instead i get an error. i know this is because php reads the code as $($var_name[1]) = 'bar'; instead of what i want it to do, which is ($$var_name)[1] = 'bar'; (round brackets in above two code examples for illustrative purposes only, not proper code) so how would i be able to do this? i dont want to do $foo[1] = 'bar'; because the value of $var_name is dynamic. any suggestions? Quote Link to comment https://forums.phpfreaks.com/topic/99951-solved-concantenating-variable-names/ Share on other sites More sharing options...
Cep Posted April 7, 2008 Share Posted April 7, 2008 Taken from the manual, 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. Quote Link to comment https://forums.phpfreaks.com/topic/99951-solved-concantenating-variable-names/#findComment-511064 Share on other sites More sharing options...
inactive Posted April 7, 2008 Author Share Posted April 7, 2008 Ah yes thanks Cep, the manual...forgot about that lol... Thanks... Quote Link to comment https://forums.phpfreaks.com/topic/99951-solved-concantenating-variable-names/#findComment-511066 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.