Before getting to my registration page, my users specify te number (X) of group members to be registered. Upon arriving on that page, X registration forms are generated, one for each member. So I have a first_name1
text field for the first person, then first_name2
, first_name3
, etc. In total, X first_name
fields each with a number at the end of it.
Problem is when retrieving those variables. There can be 20 people, so in my code I won't do:
$_POST['first_name1']
$_POST['first_name2']
...
$_POST['first_name20']
Instead, I'd like to do something like:
$_POST['first_name.$number']
Is it possible in PHP?
You can use arrays in your form element names like this:
<input name="first_name[]" type="text" />
<input name="first_name[]" type="text" />
<input name="first_name[]" type="text" />
In your php you can then access it by iterating over the array:
foreach($_POST['first_name'] as $index => $first_name) {
// Do something with $first_name
}
Note: you can create very complex structures using this method, this isn't just limited to the simple example above. You can even create a multidimensional array, for example:
<input name="user[0][first_name]" type="text" />
<input name="user[0][last_name]" type="text" />
$first_name_numbered = 'first_name'.$number;
$_POST[$first_name_numbered];
This topic has been handled well on the PHP site itself:
http://www.php.net/manual/en/reserved.variables.post.php#87650