Junaid Ali Junaid Ali - 7 months ago 26
PHP Question

How to convert weekdays to binary representation and vise versa using PHP

I am looking for PHP class that could convert any combination of weekdays to binary and vise versa

0 (for Sunday) through 6 (for Saturday)

Example:


  • Monday, Tuesday, Wednesday, Thursday, Friday => 0111110 (where sunday and saturday is off day)

  • 0101010 => this binary represents Monday, Wednesday , Friday is ON other are OFF days



The class should be able to convert the binary to weekdays and weekdays to binary

The class could have two methods:


  • public function convertWeekdaysToBinary($days)


    • This one will convert the coming days (array) to binary (string)


  • public function convertBinaryToWeekdays($binary)


    • This one will convert the coming binary (string) to days (array)



Answer

This is for first:

$arr = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

$search1 = "Monday, Tuesday, Wednesday, Thursday, Friday";
$search_arr = explode(", ", $search1);
$out1 = array("0","0","0","0","0","0","0");
foreach($search_arr as $value){
    $sr = array_search($value, $arr);
    $out1[$sr] = "1";
}
echo implode("", $out1); //0111110

Vice-versa

$search2 = "0101010";
$search_arr = str_split($search2);
$out2 = array();
foreach($search_arr as $key => $value){
    if($value == 1){
        $out2[] = $arr[$key];
    }
}
echo implode(", ", $out2);//Monday, Wednesday, Friday