Dynamic 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
rangler123
Forum Newbie
Posts: 3
Joined: Sun May 17, 2015 7:02 pm

Dynamic Variables

Post by rangler123 »

I have an array of objects -> $questions
Each object is an associative array, containing keys such as Answer1, Answer2, Answer3.. etc.

In order to get the answer for first question, I will access it as $questions[0]->Answer1

In my code, array index is dynamic and the answer number is dynamic something like this: $questions[$q]->Answer.$i

But I am not able to get the correct value with this.

I tried like this:
$q = 0;
$i = 1;
$temp = '$quesetions['.$q.']->Answer'.$i;
$value = ${$temp};

It throws the "Undefined Variable: $questions[0]->Answer1" error.
But If try to echo $questions[0]->Answer1, I get the correct value.

What is wrong in my code snippet above?

Thanks in advance.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Dynamic Variables

Post by requinix »

Can you make Answers be an array too? That's really the easiest way.
rangler123
Forum Newbie
Posts: 3
Joined: Sun May 17, 2015 7:02 pm

Re: Dynamic Variables

Post by rangler123 »

That whole thing is an object (different column values) which I get from DB.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Dynamic Variables

Post by Christopher »

You can access object properties using array syntax, so do: $questions[0]['Answer'.$i]
(#10850)
rangler123
Forum Newbie
Posts: 3
Joined: Sun May 17, 2015 7:02 pm

Re: Dynamic Variables

Post by rangler123 »

Thank you for your reply.

But this worked in the following way:
$questions[$qno]->{'Answer'.$i}
Post Reply