Holycrabbe Holycrabbe -4 years ago 67
PHP Question

PHP automatic generate names for input functions

Hey guys :D

I'm writing some self generating html input tags, and i therefor need a way to speak to these, so that i can grab the text written by the user

I have tried to do like this, but it doesn't seam to work as planed, any good ideas ?

$Content = $number.$i;
$Sum = $_POST[$Content];
$Total = $Total + $Sum
Echo $Total;

The idea here is, that i have auto generated input functions named "number1", "number2" and so on, i then want to grab all of those and get their value: anybody know a way around this ?

Thanks no matter what the answer might turn out to be

Answer Source

I and many others have been down the path of variable variables when just learning, and yes it's possible. But this is what arrays are for. Define your inputs as an array:

<input type="text" name="number[]">
<input type="text" name="number[]">

Then just loop them:

$total = 0;
foreach($_POST['number'] as $number) {
    $total += $number;

If you want to define the key and use that for some reason:

<input type="text" name="number[1]">
<input type="text" name="number[2]">

Then you could use your style of loop or:

$total = 0;
foreach($_POST['number'] as $key => $number) {
    // use $key somehow
    $total += $number;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download