Page 1 of 1
How to program a variable variable???
Posted: Tue Jul 29, 2003 10:24 am
by Tienus
I know that the following script doesn't work. But how do I get it to return "1234" on the last line? The last line should be interpreted as $AnyArray["justARandomKey"], but how
// Init var $AnyArray as an array
$AnyArray = Array();
// Init vars for referencing
$nameArray = "AnyArray";
$nameKey = "justARandomKey";
$value = "1234";
// set the original array
$AnyArray[$nameKey] = $value;
// get the array by referencing values
echo $nameArray[$nameKey];
Re: How to program a variable variable???
Posted: Tue Jul 29, 2003 10:27 am
by nielsene
Tienus wrote:I know that the following script doesn't work. But how do I get it to return "1234" on the last line? The last line should be interpreted as $AnyArray["justARandomKey"], but how
// Init var $AnyArray as an array
$AnyArray = Array();
// Init vars for referencing
$nameArray = "AnyArray";
$nameKey = "justARandomKey";
$value = "1234";
// set the original array
$AnyArray[$nameKey] = $value;
// get the array by referencing values
echo $nameArray[$nameKey];
echo $$nameArray[$nameKey];
Posted: Tue Jul 29, 2003 10:31 am
by RFairey
Put single quotes round the variable $nameKey:
Code: Select all
<?php
$AnyArray['$nameKey'] = $value;
echo $nameArray['$nameKey'];
?>
At a guess.
Doesn't work for me
Posted: Tue Jul 29, 2003 10:31 am
by Tienus
Sorry Eric, but I tried that allready and it didn't work.
What am I doing wrong

Re: Doesn't work for me
Posted: Tue Jul 29, 2003 10:38 am
by nielsene
Tienus wrote:Sorry Eric, but I tried that allready and it didn't work.
What am I doing wrong

Code: Select all
<?php
error_reporting(E_ALL);
$AnyArray=array();
$nameArray = "AnyArray";
$nameKey="aKey";
$value=1234;
$AnyArray[$nameKey]=$value;
echo ${$nameArray}[$nameKey];
?>
Normally $$varname works for variable variables. However the array index operation hapens before the variable name resolution, so you have to use braces to force the variable variable resolution before the indexing.
Didn't test before teh earlier post. This one works.
Works like a charm
Posted: Tue Jul 29, 2003 10:41 am
by Tienus
I tried doing some things with the braces and the extra $ but never had the right combination or order with them
Thanks for helping me out on this one

Posted: Tue Jul 29, 2003 4:49 pm
by RFairey
Ah - I see whats going on - you wanted indirection for arrays.
I didn't understand the question at first, thats why my previous posts are less than helpful - sorry.