Variable Variables issue

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
invisibled
Forum Contributor
Posts: 112
Joined: Sun Apr 29, 2007 3:35 pm
Location: New Westminster

Variable Variables issue

Post by invisibled »

Hey all,

so i will describe my problem as best i can, i'm certain is very simple, i'm just missing a key point or something. So i am making an application that makes quizzes. so the user enters in their question, and then enter's in 4 answers and chooses the correct answer from a set of radio buttons named answer[]

if there are multiple questions (witch there always will be... cause its a quizz) then all the radio buttons have the same answer[] name and thus you can only select 1 radio button across all of the questions when i need to select 1 radio button per question. So i fixed this by incrementing a number for each question. so if their are 4 questions posted, the will output will have answer0[], answer1[], answer2[], answer3[].

now those numbers are sync'ed up with a php while loop increment.

MY PROBLEM
I need to dynamically make variable $answer0[], 1, 2, 3 by putting the $i variable in their somewhere so that i can insert it into a mysql db. from what i understand you can do this using http://www.php.net/manual/en/language.v ... riable.php but i can't figure it out.

Can anybody give me any insight? Please ask questions if you dont understand so i can try and explian it better. Thanks! :)
invisibled
Forum Contributor
Posts: 112
Joined: Sun Apr 29, 2007 3:35 pm
Location: New Westminster

Re: Variable Variables issue

Post by invisibled »

figured it out. i used $v = ${'answer'.$i}; inside of the while loop and the put $v[0] inside of the query. :)
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Variable Variables issue

Post by requinix »

By the way: you're doing it wrong. The whole answer1, answer2, answer3 thing.
And it's not so much that it's wrong but that it's harder than it could be.

Code: Select all

<input type="radio" name="answer[1]" value="A" />
...
 
<input type="radio" name="answer[2]" value="A" />
...
 
<input type="radio" name="answer[3]" value="A" />
...

Code: Select all

// $_POST["answer"] is an array with $_POST["answer"][question number] => answer chosen
foreach ($_POST["answer"] as $question => $answer) {
    echo "You selected {$answer} as the answer to question #{$question}<br>\n";
}
Post Reply