Search code examples
phpcodeigniter-2

how to make check box depends on days of week , knowing that i store as an array?


i wanna display check box of weekdays - that display the week checked and the other days not checked

$days = $user->work_days;
$real_days = explode(',', $days);
$week = array('Saturday','Sunday' ,'Monday','Tuesday' ,'Wendnesday' ,'Thursday' ,'Friday');
for ($i = 0; $i < count($week) ; $i++) {
if (count($real_days) <= $i and  isset($real_days[$i]) and $real_days[$i] ==$i ) {
echo "<input type='checkbox' name='working_days[]' value='$i' checked >" .$week[$i]." <br>"; }else{
 echo "<input type='checkbox' name='working_days[]' value='$i'  >".$week[$i]." <br>";
}
 }

Solution

  • Here's a solution, btw you should avoid rewriting the same code twice ;)

    <?php
    $days = 'Monday,Wendnesday';
    $real_days = explode(',', $days);
    $week = array('Saturday','Sunday' ,'Monday','Tuesday' ,'Wendnesday' ,'Thursday' ,'Friday');
    //foreach is more readable
    foreach ($week as $dayName) {
        $checked = '';
        //Check if current week day is in real_days
        if (in_array($dayName, $real_days)) {
            $checked = ' checked="checked" ';
        }
        ?>
        <input type='checkbox' name='working_days[]' <?= $checked ?> ><?= $dayName ?><br>
        <?php
    }