Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Variable Variables not working when indexing arrays



9:45 pm on Apr 23, 2011 (gmt 0)



$a = 99;
$array99 = array();
$array99[] = 1;
$array99[] = 2;
$array99[] = 3;

echo "$array$a[2]";
echo "$array99[2]";

Why does the 2nd echo work and return 3, whilst the first echo returns nothing? This only seems to fail when I'm indexing arrays.


9:52 pm on Apr 23, 2011 (gmt 0)

Try it like this:

echo "${'array'.$a[2]}"


9:56 pm on Apr 23, 2011 (gmt 0)

It still doesn't work I'm afraid - thanks for trying. Are there any other ways to reference variables - maybe that is the problem?


10:02 pm on Apr 23, 2011 (gmt 0)

You could always write:

$str = "array$a".'[2]';
echo $$str;


10:06 pm on Apr 23, 2011 (gmt 0)

Thanks, but unfortunately that doesn't work either. There seems to be something that causes it give an empty output when there is a variable within the array name (which is also a variable).


10:15 pm on Apr 23, 2011 (gmt 0)

Looks like you're right, I now recall having such problem and I solved it using eval function.

eval('echo $array'.$a.'[2];');

I'm not sure about semi-colon, so this might be the one:

eval('echo $array'.$a.'[2]');


10:18 pm on Apr 23, 2011 (gmt 0)

Brilliant - I think the first of these works - now to see if I can nest the eval function within a variable name!


10:34 pm on Apr 23, 2011 (gmt 0)

Okay, so this function:
eval('echo $array'.$a.'[2];');
Works to echo the value.

If I wanted to set a new variable $alpha to be equal to the value outputted by [eval('echo $array'.$a.'[2];'); ] then how would I do this please?

$alpha = ?



11:01 pm on Apr 23, 2011 (gmt 0)

eval('$alpha = $array'.$a.'[2];');


11:18 pm on Apr 23, 2011 (gmt 0)

Thanks for your help mbabuskov - I think I finally have my function working! Off to bed now.


1:34 pm on Apr 28, 2011 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

You really don't need to use eval in this case. mbabuskov almost had it on the first attempt. The correction is that you need to assemble the string [php.net] variable name first, then wrap it in the braces:
echo ${"array$a"}[2]; 
// or for even more readability ...
echo ${"array{$a}"}[2];

Featured Threads

Hot Threads This Week

Hot Threads This Month