Jump to content

Checkbox inputs to Array


foxhill

Recommended Posts

In general, this is how it basically works:

<?php
  echo "<pre>";
  print_r($_POST);
?>
<form action = '' method = 'post'>
  <input type = 'checkbox' name = 'something[]' value = '1' /> one <br/>
  <input type = 'checkbox' name = 'something[]' value = '2' /> two <br/>
  <input type = 'checkbox' name = 'something[]' value = '3' /> three <br/>
  <input type = 'submit' value = 'submt' name = 'submit' />
</form>

 

Notice in the name attribute of the checkbox elements, you have a generic "something[]" for each one.  If you check for instance value 1 and 3, you will get a 2 element array $_POST['something'][0] and $_POST['something'][1].  If you want to specifically keep track of which ones were tracked, you can explicitly name the array like so:

 

<?php
  echo "<pre>";
  print_r($_POST);
?>
<form action = '' method = 'post'>
  <input type = 'checkbox' name = 'something[1]' value = '1' /> one <br/>
  <input type = 'checkbox' name = 'something[2]' value = '2' /> two <br/>
  <input type = 'checkbox' name = 'something[3]' value = '3' /> three <br/>
  <input type = 'submit' value = 'submt' name = 'submit' />
</form>

 

This will cause all checked values to be posted to the specific elements.

If you do this:

<form action = '' method = 'post'>
  <input type = 'checkbox' name = 'something[1]' value = '1' /> one <br/>
  <input type = 'checkbox' name = 'something[2]' value = '2' /> two <br/>
  <input type = 'checkbox' name = 'something[3]' value = '3' /> three <br/>
  <input type = 'submit' value = 'submt' name = 'submit' />
</form>

And you check 1 and 3, you will get this:

 

$_POST['something'][1] => 1

$_POST['something'][3] => 3

 

So yes, you will be able to do for instance, this:

 

if (isset($_POST['something'][2])) { ...}

 

or whatever.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.