25

So that in PHP I can deal with them as :

foreach($_POST['checkboxname'] as $i => $value)
...
user198729
  • 61,774
  • 108
  • 250
  • 348

5 Answers5

47

Do something like this:

<input type="checkbox" name="checkboxArray[]" />

Note the [] in the name.

user240609
  • 1,060
  • 10
  • 17
  • 15
    +1 Great answer. @unknown Just remember that if none of them are checked, the field won't even be submitted causing the `foreach` to fail. Be sure to test `isset($_POST['checkboxname'])` prior to the `foreach`. – Doug Neiner Dec 30 '09 at 06:58
13

Like this:

<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />

Just append [] to their names.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 4
    There is a little problem !! if i check 5th check box it should be some thing like `Array ( [4] => on )` but it display `Array ( [0] => on )` why it is should i please values like `checkboxname[1] ` and `checkboxname[2]`??? – Bilal Maqsood Sep 26 '15 at 17:07
4

If you use an array for the checkboxes, you should add a value option as identifier for the single checkboxes, because then the returned array changes from Array ( [0] => on, [1] => on) to Array ( [0] => value1, [1] => value5 ), which let you identify the checked checkboxes.

JestaBlunt
  • 143
  • 2
  • 11
3

<html>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script>
  $(document).ready(function(even){
      $("button").click(function(){
            var checkvalue = [];
            $.each($("input[name='1']:checked"), function(){            
                checkvalue.push($(this).val());
            });
            alert("checkvalue: " + checkvalue.join(", "));
        });
  });
 </script>
 <body>
  <input type="checkbox" name="1" value="1" > 1 <br/>
  <input type="checkbox" name="1"  value="2"> 2 <br/>
  <input type="checkbox" name="1"  value="3"> 3 <br/>
  <button type="button">Get Values</button>
 </body>
</html>
1

for those HTML form elements that can send multiple values to server (like checkboxes, or multiple select boxes), you should use an array like name for your HTML element name. like this:

<input type="checkbox" name="checkboxname[]" />

also it is recommended that you use an enctype of "multipart/form-data" for your form element.

<form enctype="multipart/form-data" action="target.php" method="post">

then in your PHP scripts you can access the multiple values data as an array, just like you wanted.

farzad
  • 8,775
  • 6
  • 32
  • 41