Multiple inputs with same name through POST in php
Is it possible to get multiple inputs of the same name to post and then access them from PHP? The idea is this: I have a form that allows the entry of an indefinite number of physical addresses along with other information. If I simply gave each of those fields the same name across several entries and submitted that data through post, would PHP be able to access it?
Say, for example, I have five input on one page named "xyz" and I want to access them using PHP. Could I do something like:
$_POST['xyz'][0]
If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".
Solution 1:
Change the names of your inputs:
<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum" />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />
Then:
$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'
If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".
Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.
Solution 2:
In your html you can pass in an array for the name i.e
<input type="text" name="address[]" />
This way php will receive an array of addresses.
Solution 3:
Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:
<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin" />
<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />
The outcome would be
$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'],
'city' => [ 'Berlin' , 'New York'] ];
To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:
<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin" />
<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />
The outcome would be
$POST = [ 'address' => [
1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
2 => ['street' => 'Wallstreet', 'city' => 'New York'],
]
]