using "global" with variable variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rcbowman
Forum Newbie
Posts: 1
Joined: Sat Sep 06, 2008 7:06 pm

using "global" with variable variables

Post by rcbowman »

Hello, all -

I'm trying to understand the variable variables idea a bit better, because it seems very useful.

But I'm not sure what's going on here. I have a set of different arrays full of my data. Each array has a different name. I have different functions which need to take inputs, figure out which array to look at based on the inputs, and pull that array to work on.

What I tried to do was
<?php
$myarray1=array(....)
$myarray2=array(.....)
$yourarray1=array(......)
$yourarray2=array(.......)
...
// get $whose and $num from inputs
...
function findarray($whose,$num)
{
$arrayname=$whose.'array'.$num;
global $$arrayname;
...
dostuffwith $$arrayname;
...
}
?>

But this doesn't work. Within the function a print_r($$arrayname) or various different syntaxes trying to do the same thing (print_r(${$arrayname}), or setting $thisarray=$$arrayname after the global statement, for example) all output 0 or nothing at all. So the function hasn't gotten the array from the global scope. Is this just some odd issue of syntax, or does global not work on variable variables, or am I doing something else seriously wrong?

I do realize there are other ways of doing this - in fact I've thought of several - but I'd like to know if the idea of global $$variablevariable is simply a dead end, or if there's a way to make it work.

Thanks in advance!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: using "global" with variable variables

Post by Christopher »

You could do $_GLOBAL[$whose.'array'.$num], but you should probably not be doing what you are doing at all.
(#10850)
Post Reply