ericalli
ericalli

Reputation: 1233

Decode days of the week format

I'm working with an existing scheduling system that stores a single numerical value for the days of a week that an appointment recurs.

The mapping is as follow:

Monday = 64
Tuesday = 32
Wednesday = 16
Thursday = 8
Friday = 4
Saturday = 2
Sunday = 1

So for example if the value stored for an appointment is "108" that means the appointment recurs on Monday, Tuesday, Thursday and Friday (64+32+8+4).

Is there a straightforward way I can decode the numerical value (108) in PHP to get the list of days?

Update: This value is a bitwise operator. Can PHP easily decode this?

Upvotes: 0

Views: 289

Answers (1)

monstercode
monstercode

Reputation: 964

<?php
$week = [
    'Monday' => 64, // 1000000 in binary
    'Tuesday' => 32, // 0100000 in binary
    'Wednesday' => 16, // 0010000 ...etc
    'Thursday' => 8,
    'Friday' => 4,
    'Saturday' => 2,
    'Sunday' => 1,
];

$saved_days = 108; // 1101100 in binary

$days = [];
foreach ($week as $day => $bit_value) {
    if ($saved_days & $bit_value) {
        $days[] = $day;
    }
}

var_dump($days);

The result:

array(4) {
  [0]=>
  string(6) "Monday"
  [1]=>
  string(7) "Tuesday"
  [2]=>
  string(8) "Thursday"
  [3]=>
  string(6) "Friday"
}

The idea behind this way is to make a bitmap to mark the days, so 108 = 64+32+8+4 is in binary 1101100, each bit marks a day (Monday to Sunday).

Upvotes: 4

Related Questions