Home > Article > Backend Development > How Can I Access Multiple Form Fields with the Same Name in PHP\'s $_POST Array?
When sending form data via a POST request in PHP, it's possible to encounter a situation where multiple input elements share the same name attribute. This raises the question:
Can you access the values for all fields with the same name from the $_POST array?
The answer is no. Only the last input element with the given name will be available in $_POST.
To work around this limitation, you should use name="foo[]" for the input name attribute. This will result in an array within $_POST that contains all values from the input elements with the same name. For example:
<form method="post"> <input name="a[]" value="foo"> <input name="a[]" value="bar"> <input name="a[]" value="baz"> <input type="submit"> </form>
In this case, $_POST['a'] will be an array containing the values "foo", "bar", and "baz".
It's important to note that using plain name attributes without [] will not lead to the desired behavior. This is because PHP will overwrite existing values in $_POST when encountering repeated names.
If you still need to access raw form data, you can extract it from file_get_contents('php://input'). However, you will need to manually parse this string into an array.
The above is the detailed content of How Can I Access Multiple Form Fields with the Same Name in PHP\'s $_POST Array?. For more information, please follow other related articles on the PHP Chinese website!