Home > PHP Arrays > HTML Checkbox To PHP Array

HTML Checkbox To PHP Array

To create a simple HTML check box use the following bit of code.

<input type="checkbox" name="option2" value="Milk" />

To set the checkbox as filled in include a checked attribute. To make the control XHTML compliant you will need to do the following.

<input type="checkbox" name="option2" value="Milk" checked="checked" />

When the form is posted this value is sent to PHP with the $_POST superglobal array.

To link several checkboxes together to make them into an array in the PHP $_POST array you need to make all of the checkboxes have the same name, and each name must end in "[]".

<input type="checkbox" name="option[]" value="1" />
<input type="checkbox" name="option[]" value="2" />

When both of the checkboxes are filled and the form is submitted this produces the following array.

Array
(
 [option] => Array
 (
  [0] => 1
  [1] => 2
 )
 
 [submit] => Submit Query
)

To set values in the array you can include a string in between the [] in the checkbox name.

<input type="checkbox" name="option[43]" value="1" />
<input type="checkbox" name="option[23]" value="2" />

This produces the array.

Array
(
 [option] => Array
 (
  [43] => 1
  [23] => 2
 )
 
 [submit] => Submit Query
)

Categories: PHP Arrays Tags: , , , ,
  1. Steve
    April 6th, 2011 at 17:16 | #1

    I am 4 months new to PHP! So please be gentle with me. : )

    I have an input form that contains check-boxes(it works and posts array to database correctly!) I have an update form that contains the same check-boxes (it updates and posts array to database correctly BUT IT DOESN’T CORRECTLY DISPLAY database info in the checkboxes!)

    The Problem is: I cannot get the update form to correctly display “the check-box array” from the database” It only displays the LAST unit in each array!?!?!?!?!?

    Here is my php code to pull the array from the database in a while loop (while loop works perfect and I can echo to the top of the page correctly but I want it in my html form below the php code in the HTML):

    $childarr = explode(“,”, $row["children_pref"]);
    for($i=0; $i<sizeof($childarr); $i++) {
    $children_pref = mysql_real_escape_string($childarr[$i]); }

    I have MANY of these but will just show you one…

    This is my html code for the form…

    <input type=”checkbox” name=”children_pref[]” value=”0″ >
    None
    <input type=”checkbox” name=”children_pref[]” value=”1″ > 1
    <input type=”checkbox” name=”children_pref[]” value=”2″ > 2
    <input type=”checkbox” name=”children_pref[]” value=”3″ > 3
    <input type=”checkbox” name=”children_pref[]” value=”4″ > 4
    <input type=”checkbox” name=”children_pref[]” value=”5″ > 5
    <input type=”checkbox” name=”children_pref[]” value=”6″ > 6 or more

    Any insight would be greatly appreciated.

  1. No trackbacks yet.