Home  >  Article  >  Backend Development  >  Can PHP\'s `$_POST` Array Handle Multiple Form Fields with the Same Name?

Can PHP\'s `$_POST` Array Handle Multiple Form Fields with the Same Name?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 19:48:12982browse

Can PHP's `$_POST` Array Handle Multiple Form Fields with the Same Name?

Submitting Form Fields with Duplicate Name Attributes

Question:

When submitting a form containing multiple text input fields with the same name attribute, can all field values still be retrieved from the $_POST array in PHP?

Answer:

No, only the value of the last input element with the same name will be stored in the $_POST array.

Reason:

PHP populates the $_POST array by exploding the raw query string into individual name-value pairs. When it encounters multiple name-value pairs with the same name, it overwrites the previous value with the new one.

Alternatives:

To handle multiple inputs with the same name:

  • Use a name attribute with an appended array syntax (e.g., name="foo[]").
  • Access the raw query string directly using $rawQueryString = file_get_contents('php://input').

Parsing the Raw Query String:

If using the raw query string, you can parse it manually using a script similar to:

$post = array();
foreach (explode('&', file_get_contents('php://input')) as $keyValuePair) {
    list($key, $value) = explode('=', $keyValuePair);
    $post[$key][] = $value;
}

The above is the detailed content of Can PHP\'s `$_POST` Array Handle Multiple Form Fields with the Same Name?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn