Chris
Chris

Reputation: 7310

Create array from selected checkbox values

I have a bunch of checkboxes each with a unique name and value using $_POST method. How can I put the selected values into an array? I started using a for loop, but I don't know how to call only one value at a time or determine whether it has been selected.

Upvotes: 0

Views: 380

Answers (2)

Filip Krstic
Filip Krstic

Reputation: 713

You can create a group of checkboxes.

<form id="form1" name="form1" method="post" action="">
<label><input type="checkbox" name="CheckboxGroup[]" value="checkbox" id="CheckboxGroup1_0" />Checkbox 1</label>
<label><input type="checkbox" name="CheckboxGroup[]" value="checkbox" id="CheckboxGroup1_1" />Checkbox 2</label>
</form>

And after that u can use it as you like. print_r($_POST[CheckboxGroup]);

Upvotes: 0

DaveRandom
DaveRandom

Reputation: 88657

You want to do something like this:

<input type="checkbox" name="mycheckarray[]" value="1" />
<input type="checkbox" name="mycheckarray[]" value="2" />
<input type="checkbox" name="mycheckarray[]" value="3" />
<input type="checkbox" name="mycheckarray[]" value="4" />

Check boxes 2 and 4, then at the server side, if you print_r($_POST['mycheckarray']);, you will get something like this:

Array (
  [0] => 2
  [1] => 4
)

Upvotes: 1

Related Questions