Forum Moderators: coopster

Message Too Old, No Replies

help with dynamic var name in For loop

using a var to create a var name

         

Demaestro

8:55 pm on Apr 4, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hello,

I am a bit a of a PHP n00b and I am trying to request a variable by creating the variable name in a loop and referencing it but PHP doesn't like my logic.

I have tried this 2 ways. This is within a Joomla.

I want to access vars named

this->question->answer_1, this->question->answer_2, this->question->answer_3, this->question->answer_4

this->question->feedback_1, this->question->feedback_2, this->question->feedback_3, this->question->feedback_4

Rather than just type them all out I looped it so that later if others are added I don't have to maintain the display code.

The following example shows both ways I tried creating the var name, one way is "$this->question->answer_ . $i ." the other is "$this->question->feedback_$i ." both fail

<?php for($i=1; $i<5; $i=$i+1) {
echo '<tr><td>Answer ' . $i . '</td>';
echo '<td><input type="text" size="85" name="answer_' . $i . '" value="' . $this->question->answer_ . $i . '" />';
echo '</td><td>Feedback ' . $i . '</td>';
echo '<td><input type="text" size="85" name="feedback_' . $i . '" value="' . $this->question->feedback_$i . '" /></td></tr>';
} ?>

Any suggestions on how to make this work or insight on where I am going wrong?

Thanks

Matthew1980

5:57 am on Apr 5, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Demaestro,

>>value="'.$this->question->answer_.$i.'"

So long as the value in $i is set, that should be fine, I reference some functions in much the same manner, try doing the same thing outside of the echo to see if the concatenation works - might have something to do with that. The second version is wrong though.

Cheers,
MRb