Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can't get Simple Loop to Work 1

Status
Not open for further replies.

tnsbuff

Technical User
Jan 23, 2002
216
US
I know I'm doing something simple incorrectly here, but please tell me what's wrong with the following loop where I'm trying to retrieve the variables from a form where all of the form variables are named q1 through q3:

Code:
<?
for ($i=1; $i<=3; $i++){
$q.$i = $_POST['q.$i'];
echo "$q.$i <br>";
}
?>
 
Change your code to:
Code:
<?
for ($i=1; $i<=3; $i++){
${'q'.$i} = $_POST['q'.$i];
echo ${'q'.$i} . "<br>";
}
?>
The above should work.

You might want to re-think your form definition, for example if you have:
Code:
<input type=text name=q1>
<input type=text name=q2>
<input type=text name=q3>
You could change it to
Code:
<input type=text name=q[]>
<input type=text name=q[]>
<input type=text name=q[]>
and then use
Code:
$q = $_POST['q'];
and reference the array $q

Ken
 
Thanks Ken, that works great. Unfortunately, I've never seen curly braces around the concatenated variables like that, but I guess it makes sense to set the $ sign apart.

I did find a different suggestion in my book that I thought was intended for this type of purpose. It went like the following (but I couldn't get it to work):

for ($i=1; $i <+3; $i++){
$temp = "q$i";
echo $$temp."<br>";
}

I'm sure you're right about using an array for this type of situation, and I'll look into that more. I'm very new to php and use it rarely so I appreciate the help.

Thanks again for the code. It works perfectly.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top