Page 1 of 1

Variable within a variable name

Posted: Mon Sep 13, 2010 4:56 pm
by benjiw
I am trying to accomplish something that seems as though it should be very simple, but I can't seem to find a way to make it work, despite searching a number of resources.

All I'd like to do is use the name of variable within the name of another variable. So basically I have the GET function grabbing from the URL, like this:

$tickerID = $_GET['ticker'];

Now I want to define a variable like this:

$($tickerID)1Q05 = mysql_query("blah blah blah");

that's all.... Any advice? Thanks much in advance.

Re: Variable within a variable name

Posted: Mon Sep 13, 2010 5:28 pm
by Gargoyle
how about this?

Code: Select all

$tickerID .= '1Q05';
$$tickerID = mysql_query("blah blah blah");

Re: Variable within a variable name

Posted: Tue Sep 14, 2010 5:15 am
by jazzercising011
did it work?

Re: Variable within a variable name

Posted: Tue Sep 14, 2010 8:12 am
by timWebUK
That won't work Gargoyle. Needs to be done using curly brackets.

Code: Select all

$tickerID = '1Q05';
${$tickerID} = mysql_query("QUERY");

Re: Variable within a variable name

Posted: Tue Sep 14, 2010 8:47 am
by Weirdan
most likely you're looking for something like ${$tickerID . "1Q05"} = 'something';
Can't say it's good idea to use such variables, especially because you don't seem to be filtering you incoming data (in $tickerID variable).

Re: Variable within a variable name

Posted: Tue Sep 14, 2010 10:50 am
by benjiw
Thanks very much tim and Weirdan--works perfectly; thought I had tried that before, but must have made a syntax error.

Weirdan, what do you mean about filtering the incoming variable?

Thanks again.

Re: Variable within a variable name

Posted: Tue Sep 14, 2010 12:17 pm
by Gargoyle
That won't work Gargoyle. Needs to be done using curly brackets.
indeed. that's weird. did PHP change its behavior for this or do I just remember it wrong? I am sure there was a time you could do this without curly braces. strange.
Weirdan, what do you mean about filtering the incoming variable?
if you're using user input (GET data is user input), you're facing the problem of code injection, so you need to make sure the data passed by the user can't do any harm.