37 Votes

PHP: Get dynamic POST variables from form

Question by Guest | 2012-06-24 at 23:44

I have a form with a large number of input fields, most of them are numbered. Now, I would like to process the inputs within a PHP script, the data is sent using POST.

The problem: If I call the name of each input field individually, the script would be incredibly long and would look something like this:

$var1 =  $_POST['field1'];
$var2 =  $_POST['field2'];
$var3 =  $_POST['field3'];
$var4 =  $_POST['field4'];
// and so on

Isn't there the possibility to adress the names of the fields dynamically in a loop or to simplify the process in any other way?

ReplyPositiveNegativeDateVotes
46 Votes

This is quite simple. I will show you some ways, how you can proceed.

First, you can use a variable that contains the name of the input field:

$varname = 'field1';
$var1 = $_POST[$varname];

It is also possible with a loop:

for ($i=1; $i<=10; $i++) { // field1 to field10
  $name = 'field'.$i;
  $var = $_POST[$name];
  // processing of $var
}

Or with an array:

// array with the names of the input fields:
$nams = array('field1', 'field2', 'field3');
 
// first possibility
foreach ($nams as $value) {  // go through array
  $var = $_POST[$value];
  // processing of $var
}
 
// second possibility
for ($i=0; $i<3; $i++) {
  $var = $_POST[$nams[$i]];
  // processing of $var
}

Just see what you can best use in your script.
2012-06-26 at 12:50

ReplyPositive Negative
35 Votes

Alternatively, you can ensure that the data is transferred directly from the form to your script as an array. Your form can look something like this:

<form action="script.php" method="post">
  <input name="field[]" />
  <input name="field[]" />
  <input name="field[]" />
</form>

In PHP, you can save your data directly to an array to process it:

// receive all data in an array
$fields = $_POST['field'];
 
// output / process all data
foreach ($fieles as $value) {
  echo $value;
}

Just name all input fields with the same name and write [] behind. The effect is, that the data is sent as an array. Then, you can directly process the array in PHP.

Edit: More on this topic, you can read in the tipp Send input from form as an array to a PHP script.
2012-06-26 at 15:49

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.