How to count a dynamic HTML form input array with PHP?

放肆的年华 提交于 2021-01-27 17:31:27

问题


I have a button on a page that when a user pushes it, it creates another "Contact" field on the page. The Contact field allows them to add a new contact to their profile. Also, they can click the button as many times as they want, and it will create that many "Contact" fields.

The problem though is that I am having a hard time figuring how many "Contact" fileds have been added. Here is some HTML that is generated when the button is clicked:

<div class="item">
    <label for="in-1v">First Name <span>*</span></label>
    <div class="text">
        <input type="text" id="in-1-0" name="member[0][fname]" value="" />
    </div>
</div>
<div class="item">
    <label for="in-2-0">Last Name <span>*</span></label>
    <div class="text">
        <input type="text" id="in-2-0" name="member[0][lname]" value="" />
    </div>
</div>

Each time the button is clicked, name="member[0][lname]" will become name="member[1][lname]" and will continue to increment each time the button is clicked. As stated earlier, the user can do this as many times as they want on the page.

I am using PHP to loop through the multidimensional array:

$array = $_POST['member'] ;
foreach($array as $array_element) {
  $fname = $array_element['fname'];
  $lname = $array_element['lname'];
}

How can I use PHP to determine how many fileds have been added so I can loop through them?

Any help is greatly appreciated!


回答1:


You can simply get a count like so:

$count = count($_POST['member']);

You could also then modify your loop to look like this:

// First check to see if member is set and is a valid array
if (!empty($_POST['member']) && is_array($_POST['member'])) {
    $count = count($_POST['member']);
    for ($i = 0; $i < $count; $i++) {
        $fname = $_POST['member'][$i]['fname'];
        $lname = $_POST['member'][$i]['lname'];
    }
}


来源:https://stackoverflow.com/questions/13695804/how-to-count-a-dynamic-html-form-input-array-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!