Jump to content

[SOLVED] concantenating variable names


inactive

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.