首页 > 解决方案 > Assign an array to the 'name' attribute in an HTML form

问题描述

I went through some code, and I found some code snippet as follows. Here I see, an array is assigned to name attributes like name="item[] and name="item[{0}]". I think this is an array assigning to add, items values again and again. I am not sure about that since I have not been using this before. Is this an array assignment or how is it used?

This is the first part in which the form displays a field to add items.

<input type="text" class="form-control item" name="item[]" required="required" placeholder=" Item Name">

The JavaScript code is there to add a new field to enter items once Add Another Item button clicks

<script type="text/html" id="addChild">
    <input type="text" class="form-control item" name="item[{0}]" required="required" placeholder="Item Name">
</script>

Once the button clicks this above section add a new field to add items.

标签: phphtmlarraysforms

解决方案


在您的代码的第一部分是如前所述item[]。该数组从输入中一一收集数据,并以数字索引的形式对其进行排列。只是在 PHP 的情况下,索引被添加为键。

例如:如果我们在输入中选择多个项目(如 item1 和 item2),item[]则将取值并将它们排列为:

array(
    [0] => 'item1',
    [1] => 'item2'
)

推荐阅读