Variable within a variable name

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
benjiw
Forum Newbie
Posts: 4
Joined: Tue May 04, 2010 11:53 am

Variable within a variable name

Post 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.
Gargoyle
Forum Contributor
Posts: 130
Joined: Wed Jul 14, 2010 12:25 am

Re: Variable within a variable name

Post by Gargoyle »

how about this?

Code: Select all

$tickerID .= '1Q05';
$$tickerID = mysql_query("blah blah blah");
jazzercising011
Forum Newbie
Posts: 9
Joined: Tue Sep 14, 2010 4:47 am

Re: Variable within a variable name

Post by jazzercising011 »

did it work?
User avatar
timWebUK
Forum Contributor
Posts: 239
Joined: Thu Oct 29, 2009 6:48 am
Location: UK

Re: Variable within a variable name

Post by timWebUK »

That won't work Gargoyle. Needs to be done using curly brackets.

Code: Select all

$tickerID = '1Q05';
${$tickerID} = mysql_query("QUERY");
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Variable within a variable name

Post 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).
benjiw
Forum Newbie
Posts: 4
Joined: Tue May 04, 2010 11:53 am

Re: Variable within a variable name

Post 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.
Gargoyle
Forum Contributor
Posts: 130
Joined: Wed Jul 14, 2010 12:25 am

Re: Variable within a variable name

Post 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.
Post Reply