user2417624
user2417624

Reputation: 693

loop through checkboxes - how to get all checked checkboxes?

I have the following group of checkboxes:

<div class="chb_group">
   <span class="custom_chb_wrapper">
       <input class="zcheckbox" type="checkbox" value="164" name="categoriesfilters">
       <label>Air Condition A/C</label>
   </span>
</div>
<div class="chb_group">
    <span class="custom_chb_wrapper">
        <input class="zcheckbox" type="checkbox" value="165" name="categoriesfilters">
        <label>Clima</label>
   </span>
</div>
<div class="chb_group">
    <span class="custom_chb_wrapper">
        <input class="zcheckbox" type="checkbox" value="166" name="categoriesfilters">
        <label>Range Command</label>
    </span>
</div>

This is just a part from very long form. I am trying to loop trough the checkboxes with the name categoriesfilters and to get the values of the checked checkboxes that belong in this group.

I am trying with following code:

foreach ($_POST as $name=>$value) {
                    if($name == 'categoriesfilters') {
                    echo $name . " -> ".$value ."<br />";
                    }
                 }

but i am getting only the last checkbox even i check all of them. Anyone can help?

Regards, John

Upvotes: 0

Views: 1178

Answers (1)

hsz
hsz

Reputation: 152216

You should change inputs' name to name="categoriesfilters[]"

Then you can access categoriesfilters values with $_POST['categoriesfilters']

Remember that $_POST['categoriesfilters'] is an array of integers, so:

foreach ($_POST as $name=>$value) {
  if ($name == 'categoriesfilters') {
    echo $name . " -> ". implode(',', $value) ."<br />";
  }
}

Upvotes: 3

Related Questions