2

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!

5
  • Does this php work? Does it loop through the array? I was of the understanding you couldn't do multidem arrays from html to php like this. Dec 4, 2012 at 3:56
  • @shapeshifter - Yes, you can... it's perfectly valid Dec 4, 2012 at 3:57
  • Yes, the above code does loop through an multidem array
    – three3
    Dec 4, 2012 at 3:57
  • Anybody have documentation to support this? Dec 4, 2012 at 3:58
  • 1
    Here you go: php.net/manual/en/faq.html.php#faq.html.arrays Dec 4, 2012 at 3:58

1 Answer 1

6

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'];
    }
}
2
  • I was going to say this too, but I don't think you can have multidimensional arrays from html to php like this. Does this actually work? Dec 4, 2012 at 3:56
  • @shapeshifter - Yep, as I said above, you can. Dec 4, 2012 at 3:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.