[thelist] php: how to reselect a checkbox on page reload

Kelly Hallman khallman at wrack.org
Sat Aug 9 11:34:14 CDT 2003

On Sat, 9 Aug 2003, Dunstan Orchard wrote:
> I'm stuck on how to re-select the checkboxes that the user had chosen
> before hitting submit. I can do it on a case-by-case basis, but I'd
> rather use a little function. Can anyone suggest a solution? I'm sure it
> involves arrays, it always does.

Dunstan, this should do what you're looking for, based on the example that 
you provided.  I didn't test this code, but it should be pretty close.

function checkbox_group($cbarr,$formitem,$formname) {
    foreach($cbarr as $k => $v) {
        $ret.= '<input type="checkbox" name="'.$formname.'" id="'.$k.
            '" value="'.$v.'" '. (is_array($formitem) &&
            in_array($v,$formitem)?"CHECKED ":""). '/>\n'; }
    return $ret; }

$chkboxes = array(
    "bandc_cat" => "Barrel and Container Pumps",
    "lab_cat"   => "Laboratory Pumps",
    "sanit_cat" => "Sanitary Pumps" );

echo checkbox_group($chkboxes,$_POST['cat'],"cat[]");

Hope that helps...!

Kelly Hallman

More information about the thelist mailing list