By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,747 Members | 2,039 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,747 IT Pros & Developers. It's quick & easy.

array access via strings

P: n/a
Hi,

I would like to access an array via an index I have in a string. I know I
can pull the string apart and manually access it but that just looks ugly to
me :)

$pg['owner']['email'] = "fo*@bar.com";
$row->name = "[owner][name]"; //single quotes on 'owner' haven't helped
$value = "pg".$row->name;
echo $value; //ouput: 'pg[owner][email]'

echo $$value; //ouput: '' //not what i want!
eval ("\$value = $$value;");
echo $value; //output: 'fo*@bar.com' //what i want

Now i've tried lots of ${ } stuff but I'm at a loss - why does the eval ()
code work but not the real code!!!

Cheers
--
Kyle Maddison
km**********@cam.ac.uk
http://kyle.is-a-geek.com/
Jul 16 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Hi Kyle,

the "variable variable names" approach ($$value) doesnt work, because
"pg[owner][email]" is not a name for a variable that can be looked up.
The name of your variable is "pg".

You have to take your string that holds the keys apart:
for example:
$row->name="[owner]";
$row->mail="[email]";

echo $pg[$row->name][$row->mail];
would work.

That might imply that you have to split your string
$row->name = "[owner][name]";
to get the two parts, e.g. using preg_match.

eval works, because you sort of emulate variable variables
on a source-code level.

Cheers
Frank
Kyle Maddison wrote:
Hi,

I would like to access an array via an index I have in a string. I know I
can pull the string apart and manually access it but that just looks ugly
to me :)

$pg['owner']['email'] = "fo*@bar.com";
$row->name = "[owner][name]"; //single quotes on 'owner' haven't helped
$value = "pg".$row->name;
echo $value; //ouput: 'pg[owner][email]'

echo $$value; //ouput: '' //not what i want!
eval ("\$value = $$value;");
echo $value; //output: 'fo*@bar.com' //what i want

Now i've tried lots of ${ } stuff but I'm at a loss - why does the eval ()
code work but not the real code!!!

Cheers
--
Kyle Maddison
km**********@cam.ac.uk
http://kyle.is-a-geek.com/


Jul 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.