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.

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.