View Full Version : Checkbox array

01-13-2008, 11:34 PM

I have a form with checkbox array:

<input type="checkbox" name="specialties[]" value="bla">
<input type="checkbox" name="specialties[]" value="bla bla">

Once the form is submited, I am trying to explode the array so I can use the "selected" option on the checkboxes when manditory fileds are missed.



01-14-2008, 01:54 AM
There is no 'selected' attribute in php, checkboxes are not considered objects per se, but instead a single entity.
So, to retrieve your values would be via $_POST/$_GET['specialities']. The specialites index is a type of array and can be iterated through. Each value should correspond to a value that has been checked:

'specialities' => array(
[0] => 'bla',
[1] => 'bla bla'

So you can explode the values if you want: $vals = explode($_POST/_GET['specialities']);
Would be the value of the _REQUEST['specialties'] array if both of these options are selected. Be warned, if only one option is selected, the value will still be an array as you have specified in the html as it being such.

01-14-2008, 03:40 AM

I tried:

if (is_array($_POST['special'])) {
$a = implode(",", $_POST['special']);

<input type="checkbox" name="special[]" '.( $a=='test' ? 'selected' : '' ).' value="test">

Remains unselected. Is that the right concept?


01-14-2008, 05:07 AM
Yes, thats incorrect, remember that implode will put your pieces together, so you need to check it on each individual item.
Just check to see if its in the array:

$checked = array();
if (!is_array($_POST['special']))
$checked = $_POST['special'];
// Don't know what else you want to do with this, so we'll just shove it in a var:
$checkbox = '<input type="checkbox" name="special[]" value="test" ' . in_array('test', $checked) ? 'checked="checked"' : '' . '/>';

To shorten it up, you may want to stick all of the checkbox values into an array as well:

$aChkVals = array(
$checkboxes = '';
foreach ($aChkVals AS $chkVals)
$checkboxes .= // All that input stuff here

Kill two birds with one stone ;)

01-14-2008, 05:58 AM

Im not really following ...

I have alot of check boxes .. ie:

<td bgcolor="#F2F5F9"><input type="checkbox" name="specialties[]" value="Retail/Shopping"></td>
<td align="left" bgcolor="#F2F5F9" class="small_10">Retail/Shopping</td>
<td bgcolor="#F2F5F9"><input type="checkbox" name="specialties[]" value="Solar Design"></td>
<td align="left" bgcolor="#F2F5F9" class="small_10">Solar Design</td>
<td bgcolor="#F2F5F9"><input type="checkbox" name="specialties[]" value="Sports/Athletic Facilities"></td>
<td align="left" bgcolor="#F2F5F9" class="small_10">Sports/Athletic Facilities</td>

And dont want to break out of the echo ..