|  | Posted by Tim Hunt on 07/14/06 13:27 
jeffsnox@gmail.com wrote:> Hi,
 >
 > I have multiple checkboxes on the same form as follows:
 >
 > <input type='checkbox' name='cbtype[]' value='1'>
 > <input type='checkbox' name='cbtype[]' value='2'>
 > <input type='checkbox' name='cbtype[]' value='3'>
 >
 > I'm wanting to re-display the same checkboxes, but if the user
 > previously checked one of them then I want it automatically checked on
 > the subsequent display. At the moment I'm doing this:
 >
 > $checked = '';
 > if (in_array('1',$HTTP_POST_VARS[cbtype])) { $checked = ' checked'; }
 > <input type='checkbox' name='cbtype[]' value='1' $checked>
 >
 > This works perfectly unless the user hasn't selected any of the
 > checkboxes in which case I get the following error thrown at me:
 >
 > Warning: in_array(): Wrong datatype for second argument in...
 >
 > Obviously PHP isn't creating an array for the checkbox selection data
 > unless it has to, and so "in_array" is throwing a wobbly.
 >
 > Presumably there's a better way to do this?
 >
 > TIA
 
 Hiya
 
 Use isset to check cbtype is in the post vars to avoid the warning
 
 Another way is echo + check the checkboxes in a loop....The more
 checkboxes to show the more useful it is to loop
 
 $checkboxLabels = ( 1 => 'Label1', 'Label2', 'Label3' );
 $cbtype_set = isset($_POST['cbtype']);
 
 foreach( $checkboxLabels as $id => $label ) {
 $checked = ( $cbtype_set && in_array($id, $_POST['cbtype'])  ) ? '
 checked="checked"' : '';
 
 echo '<input type="checkbox" name="cbtype[]" value="', $id , '",
 $checked, '>',$label;
 }
 
 Tim
 [Back to original message] |