Selecting variables dynamically?

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
hider
Forum Newbie
Posts: 7
Joined: Fri Jun 18, 2010 9:11 am

Selecting variables dynamically?

Post by hider »

I don't know how best to explain this, but I have a few variables like this:

Code: Select all

$question1, $question2, $question3.. etc.
Now, I want to run a forloop, and select each 'question' variable respectively inside the for loop.. but I don't know how to do this?

The 'counter' variable in the forloop is $j, and I was thinking something along the lines of:

Code: Select all

$question$j
But it doesn't work.. any help?
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: Selecting variables dynamically?

Post by cpetercarter »

Ah, variable variables!

Try

Code: Select all

${$question.$j}
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Selecting variables dynamically?

Post by AbraCadaver »

Yes, variable variables are cool, but normally if you need to use them, an array would be a better and easier solution. Where are these question variables coming from?
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
hider
Forum Newbie
Posts: 7
Joined: Fri Jun 18, 2010 9:11 am

Re: Selecting variables dynamically?

Post by hider »

AbraCadaver wrote:Yes, variable variables are cool, but normally if you need to use them, an array would be a better and easier solution. Where are these question variables coming from?
Of course, I can just turn them into an array.. what was I thinking. Haha.

Cheers :)
Post Reply