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!

Dynamically Read Variables

Status
Not open for further replies.

Wickersty

Programmer
Nov 13, 2002
51
US

Hi.

Say I have a FORM that passes three variables:

var1, var2, and var3

I want the PHP page that reads the form to LOOP through and read each one.

What I have is:

$i=0;
while($i < 3) {
$tempVar=&quot;$var&quot; . $i;
echo(&quot;var&quot; . $i . &quot;= &quot; . $tempVar . &quot;\n&quot;);
echo(&quot;<BR>\n&quot;);
$i=$i+1;
}


This doesn't work, obviously, and I can't figure out how to make PHP make $tempVar equal to what in essence is: &quot;$var&quot; . $i;

Can anyone help me out on this?

Thanks,

Jeff
 
<?php

$var0=&quot;hey&quot;;
$var1=&quot;you&quot;;
$var2=&quot;guys&quot;;

$i=0;
while($i<3) {
$temp=${&quot;var$i&quot;};
echo $temp.'<br>';
$i++;
}
?>

-Ryan
 
There is an alternative in PHP.

If you have an HTML form submitting to a PHP script of the form:

Code:
<html><body>
<form method=POST action=yourscript.php>
<input type=text name=&quot;var[0]&quot;>
<input type=text name=&quot;var[1]&quot;>
<input type=text name=&quot;var[2]&quot;>
<input type=submit>
</form></body></html>

Then the three values returned from the inputs will appear in PHP as three elements in an array named &quot;var&quot; (in $_POST[&quot;var&quot;] always and in as $var if you have register_globals set to &quot;on&quot; in php.ini)

You can use either numbers or strings inside the square boxes so that you can specify the elements individually.

If you leave the square boxes empty (i.e. name all three inputs &quot;var[]&quot;), PHP will assign the values in the order they are passed from the browser.  This can be useful for checkboxes -- set the names of a group of checkboxes all the same, but give them different values.  Just the values that were checked will appear in the array in your script.

One gotcha.  If you name these form elements all the same, it is difficult to reference them via JavaScript. [i]Want the best answers?  Ask the best questions:[/i] [URL unfurl="true"]http://www.tuxedo.org/~esr/faqs/smart-questions.html[/URL]
TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top