Home >Backend Development >PHP Tutorial >How Does HTML's `name='foo[]'` Syntax Create Arrays in PHP?
Arrays of Input Fields in HTML
The use of HTML input fields with the name="foo[]" syntax has been a common practice, but its proper terminology and specification have remained elusive. Contrary to common belief, this feature is not part of the HTML 4.01 specification and does not fall under any official HTML standard.
Instead, this syntax is an artifact of PHP's behavior in parsing HTML form data. When rendered on a web page, the name="foo[]" attribute creates multiple input elements with the same name, representing an array in PHP. For example:
<input type="checkbox" name="food[]" value="apple" /> <input type="checkbox" name="food[]" value="pear" />
After submission, PHP assigns the selected values to an array called $_POST['food'], and you can access its elements as follows:
echo $_POST['food'][0]; // Output the value of the first selected checkbox
To iterate over all selected values:
foreach ($_POST['food'] as $value) { print $value; }
Although this behavior is widely used, it does not have a specific name within the HTML specification. It remains a PHP-specific convention for representing arrays in HTML forms.
The above is the detailed content of How Does HTML's `name='foo[]'` Syntax Create Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!