DiigIT | IT Community
No Profile Image
Welcome Guest
New User? Register | Login

display variable based on loop variable

By: | 18 Feb 2009 4:25 pm

Hi,

I am trying to automatically display a variable, based on the value of $i
variable in a loop. For example, I have $q1, $q2, $q3, $q4 variables and so on.
So what I want is, to display $q1 if $i=1, display $q2 if $i=2 and so on...How
can I do that? I tried creating a separate new variable to make $new=$q($i) or
something like that but it gives error. Or I tried doing $new="$q".$i; but this
time when I echo $new, it only gives the value of $i.

How can I display the correct $q variable based on the value of $i?

Thanks

Comments

I am trying to automatically display a variable, based on



This trick is not unique to PHP but it can be helpful in cases like this.

print $q{$i};

The contents of the curly braces are evaluated. Here is some sample code:

<?php
$q1=52; $q2=22; $q3=83; $q4=2; $q5=37;
foreach (range(1,5) as $i)
{
print "$q{$i}n";
}
?>

When you have data like this, it is often better to store it in an array.

By: | 18 Feb 2009

I also found another way, like this:
$new = array(0,$q1,$q2,$q3,$q4,$q5,$q6,$q7,$q8);
echo "<form method="post" action="updateanswers.php">";
for($i=1; $i<=$qtotal; $i++)

{

$answer="answer".$i;
echo "<input type="radio" name="answer" value=$answer>";
echo $new[$i];
echo "</br>";

}

By: | 18 Feb 2009

Leave a comment

Enter the text in the image
img
Can't read?
Type the characters you see in the picture below.


Close Move