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.
Dynamic Variables
Moderator: General Moderators
Re: Dynamic Variables
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
That whole thing is an object (different column values) which I get from DB.
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Dynamic Variables
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
Thank you for your reply.
But this worked in the following way:
$questions[$qno]->{'Answer'.$i}
But this worked in the following way:
$questions[$qno]->{'Answer'.$i}