Jump to content

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/99951-solved-concantenating-variable-names/
Share on other sites

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.