2

I have a list of checkboxes with weekdays name and those values are [1,2,4,8,16,32,64]

<label class="m-checkbox">
    <input type="checkbox" name="selected_days[]" value="1" id="check_sun"/>Sunday<span></span>
</label>
<label class="m-checkbox">
    <input type="checkbox" name="selected_days[]" value="2" id="check_mon"/>Monday<span></span>
</label>
<label class="m-checkbox">
    <input type="checkbox" name="selected_days[]" value="4" id="check_tue"/>Tuesday<span></span>
</label>

<label class="m-checkbox">
    <input type="checkbox" name="selected_days[]" value="8" id="check_wed"/>Wednesday<span></span>
</label>
<label class="m-checkbox">
    <input type="checkbox" name="selected_days[]" value="16" id="check_thu"/>Thursday<span></span>
</label>
<label class="m-checkbox">
    <input type="checkbox" name="selected_days[]" value="32" id="check_fri"/> Friday<span></span>
</label>
<label class="m-checkbox">
    <input type="checkbox" name="selected_days[]" value="64" id="check_sat"/> Saturday<span></span>
</label>

While saving them I make a sum of selected checkboxes to store in DB

<?php array_sum($post_data["selected_days"]);?>

So the problem is while getting the day I get some of the select checkboxes right. I am unable to find how to display selected checkboxes with the sum

Ex: Mon, Tue and Sat selected So the DB value will be 70 (2+4+64) When I get from DB it will be 70. How do I know those are Mon, Tue & Sat only

Please help me to do it

Praveen Kumar
  • 864
  • 2
  • 9
  • 33

2 Answers2

2

You can do it by using bit wise operators

DB Sum Column & Input Day = Input Day
70 & 4 = 4
70 & 2 = 2
70 & 64 = 64

For other days the value will be 0.

Update

$daysArr = [1=>'Sunday', 2=>'Monday', 4=>'Tuesday', 8=>'Wednesday', 16 => 'Thursday', 32=>'Friday', 64=>'Saturday'];
$selectedArr = [];
$dbData = 70; //Your db result here
foreach($daysArr as $selDay => $selDayName)
{
    if($dbData & $selDay){
        $selectedArr[] = $selDay;
    }
}

print_r($selectedArr);

PHP code to check this for dynamic values.

balakrishnan
  • 383
  • 4
  • 12
1
$sum = 29;
$days = array("Sun","Mon","Tue","Wed","Thur","Fri","Sat");
$selected = str_split(decbin($sum));
$count = count($selected);
echo "Checked days are "; 
for($i=0;$i<=$count-1;$i++){
    if($selected[$i]==1){
    echo $days[$i] ." ";
    }
}
Twista
  • 241
  • 3
  • 11