Home » Php » How can I use the array-format input field names in my HTML form that posts to PHP?

How can I use the array-format input field names in my HTML form that posts to PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I understand the basics of using the array-formatted HTML input names. If I had a form with a variable number of ‘item’ inputs I might do something like this for each of them:

<input name='item[]' type='text' />

And when I retrieve the items from the $_POST array I could iterate over them like so:

$items = $_POST['item'];
foreach($items as $item) {
}

But my question is slightly more complicated. I have a form where users can click a button “add one” and a new row will appear at the bottom number of the form. Each new row contains a ‘name’ and ‘description’ input.

So initially I thought I would do this:

<input name='item[name][]' type='text' />
<input name='item[description][]' type='text' />

And then iterate over them like so:

$items = $_POST['item'];
foreach($items as $item) {
  print $item['name'] . ' ' . $item['description'];
}

But instead of working as I hoped, it instead structures the ‘item’ array such that I would access the first item name as $item['name'][0] rather than as $item[0]['name'].

So then I flipped it so that my inputs were named as such:

<input name='item[][name]' type='text' />
<input name='item[][description]' type='text' />

But this resulted in a separate ‘item’ for each ‘name’ and for each ‘description’ rather than grouping each pair in a single ‘item’.

I really dislike having arrays of ‘name’ and separate array of ‘description’. I would prefer arrays of ‘item’ with each array containing a ‘name’ and a ‘description’ field. Is there any way to accomplish this without generating the an index in my javascript? Since people can add and remove these dynamically it’s very difficult for my javascript to calculate the appropriate index for the next item. Is there no way to do this generically?

How to&Answers:

It’s not possible to do what you want, but if it helps, here’s some code to piece it back together that I think will work (with item_name[] and item_description[]):

$items_desc = $_POST["item_description"];
$items_name = $_POST["item_name"];
$items = array();
for ($i = 0; $i < count($items_name); $i++)
{
    $items[] = array("name" => $items_name[$i], "description" => $items_desc[$i]);
}