Home > Backend Development > PHP Tutorial > How Do Square Brackets in HTML Input Names Create Arrays in PHP?

How Do Square Brackets in HTML Input Names Create Arrays in PHP?

Mary-Kate Olsen
Release: 2024-12-03 20:46:11
Original
1002 people have browsed it

How Do Square Brackets in HTML Input Names Create Arrays in PHP?

Unraveling the Enigma of HTML Input Arrays

In the realm of HTML forms, you may have encountered input elements adorned with the mysterious square brackets enclosing their names. This peculiar notation has raised questions about its nature and specification.

Delving into the elusive HTML 4.01 Spec, this "feature" remains conspicuously absent. Exploring Google's vast archives yielded inconclusive results, with references to "arrays" and PHP examples. It is precisely in the realm of PHP that the enigma unravels.

In PHP, input elements suffixed with square brackets are automatically parsed into arrays. This peculiarity allows form submission to encapsulate multiple selected values into a single array variable. For instance, consider the following HTML snippet:

<input type="checkbox" name="food[]" value="apple">
<input type="checkbox" name="food[]" value="pear">
Copy after login

Upon form submission, PHP will create the array variable $_POST['food'], containing the selected values. You can access individual elements with the familiar array syntax:

echo $_POST['food'][0]; // Outputs the first selected fruit (e.g., "apple")
Copy after login

Alternatively, you can iterate over all selected values using a foreach loop:

foreach ($_POST['food'] as $value) {
    print $value; // Outputs each selected fruit (e.g., "apple" and "pear")
}
Copy after login

While this behavior is invaluable for collecting multiple user selections, it's important to note that the notion of "HTML input arrays" is not part of the official HTML specification. It's a JavaScript-parsed specific implementation.

The above is the detailed content of How Do Square Brackets in HTML Input Names Create Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template