Page 1 of 1

Dynamic Variables

Posted: Sun May 17, 2015 7:18 pm
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.

Re: Dynamic Variables

Posted: Sun May 17, 2015 7:27 pm
by requinix
Can you make Answers be an array too? That's really the easiest way.

Re: Dynamic Variables

Posted: Sun May 17, 2015 8:12 pm
by rangler123
That whole thing is an object (different column values) which I get from DB.

Re: Dynamic Variables

Posted: Sun May 17, 2015 9:47 pm
by Christopher
You can access object properties using array syntax, so do: $questions[0]['Answer'.$i]

Re: Dynamic Variables

Posted: Sun May 17, 2015 10:31 pm
by rangler123
Thank you for your reply.

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