If you have a form containing text inputs with duplicate name attributes, and the form is posted, will you still be able to obtain the values of all fields from the $_POST array in PHP?
If you have a form containing text inputs with duplicate name attributes, and the
Share
No. Only the last input element will be available.
If you want multiple inputs with the same name use
name="foo[]"for the input name attribute.$_POSTwill then contain an array for foo with all values from the input elements.See the HTML reference at Sitepoint.
The reason why
$_POSTwill only contain the last value if you don’t use[]is because PHP will basically just explode and foreach over the raw query string to populate$_POST. When it encounters a name/value pair that already exists, it will overwrite the previous one.However, you can still access the raw query string like this:
Assuming you have a form like this:
the $
rawQueryStringwill then containa=foo&a=bar&a=baz.You can then use your own logic to parse this into an array. A naive approach would be
which would then give you an array of arrays for each name in the query string.