Updating Already Checked Checkboxes in PHP

后端 未结 4 1847
夕颜
夕颜 2020-12-22 03:30

let\'s say I have a list of checkboxes that the user selects.

Water<         


        
4条回答
  •  轮回少年
    2020-12-22 03:50

    What I've done in the past, to save having hundreds of lines of bloat is this...

    First compile all the html in a variable, without any "checked" instances.

    $boxes = '';
    $boxes .= 'Water
    '; $boxes .= 'Cable
    '; $boxes .= 'Electricity
    ';

    Now I loop over your array of fields to check. I've provided a sample array here too.

    $already_checked = array('Water', 'Electricity');
    
    foreach( $already_checked as $ac ) {
        $find = 'value="' . $ac . '"';
        $replace = $find . ' checked="checked"';
        $boxes = str_replace($find, $replace, $boxes);
    }
    
    echo $boxes;
    

提交回复
热议问题