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">
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")
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") }
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!