HTML input arrays

2019-01-01 09:01发布

<input name="foo[]" ... >

I've used these before, but I'm wondering what it is called and if there is a specification for it?

I couldn't find it in the HTML 4.01 Spec and results in various Google results only call it an "array" along with many PHP examples of processing the form data.

4条回答
其实,你不懂
2楼-- · 2019-01-01 09:39

As far as I know, there isn't anything on the HTML specs because browsers aren't supposed to do anything different for these fields. They just send them as they normally do and PHP is the one that does the parsing into an array, as do other languages.

查看更多
高级女魔头
3楼-- · 2019-01-01 09:45

It's just PHP, not HTML.

It parses all HTML fields with [] into an array.

So you can have

<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />
<input type="checkbox" name="food[]" value="banana" />

and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:

echo $_POST['food'][0]; // would output first checkbox selected

or to see all values selected:

foreach( $_POST['food'] as $value ) {
    print $value;
}

Anyhow, don't think there is a specific name for it

查看更多
唯独是你
4楼-- · 2019-01-01 09:48

Follow it...

<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3];  // Displaying Selected array Value
foreach ($a as $v) {
    print_r($v); //print all array element.
}
?>
查看更多
无与为乐者.
5楼-- · 2019-01-01 09:56

There are some references and pointers in the comments on this page at PHP.net:

Torsten says

"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."

Jetboy says

"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."

查看更多
登录 后发表回答