Reputation: 192
I have a character string representing the days of the week in a "binary" format. Example: 1001110.
In this example: Monday is TRUE, Tuesday, FALSE, Wednesday FALSE, Thursday TRUE, Friday TRUE, Saturday TRUE, Sunday FALSE
How to determine if the current day is true or false with the easiest and most elegant way possible.
I have already been able to convert the binary string into days of the week, then I can compare it with the current day, but I'm looking for a lighter method, (if it's possible ..)
<?php
$arr_jours = array();
$arr_jours = array(
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
);
$week = "1001110";
$search_arr = str_split($week);
$out = array();
foreach($search_arr as $key => $value) {
if ($value == 1) {
$out[] = $arr_jours[$key];
}
}
if (in_array(date('l') , $out)) {
echo "Current day is TRUE";
}
else {
echo "Current day is FALSE";
}
?>
This works but I try to make it more elegant. How can I best optimize this code?
Thanks for your help.
Upvotes: 2
Views: 275
Reputation: 146460
If you're willing to sacrifice legibility you can use binary integer literals and bitwise operators:
/**
* @param int $date Unix time
* @return bool
*/
function isActive($date)
{
$days = [1 =>
0b1000000,
0b0100000,
0b0010000,
0b0001000,
0b0000100,
0b0000010,
0b0000001,
];
$week = 0b1001110;
$day = $days[date('N', $date)];
return ($week & $day) === $day;
}
Demo.
Or you can drop binary literals to look less geek and just use bitwise operators:
/**
* @param int $date Unix time
* @return bool
*/
function isActive($date)
{
$days = [1 => 64, 32, 16, 8, 4, 2, 1];
$week = bindec('1001110');
$day = $days[date('N', $date)];
return ($week & $day) === $day;
}
Upvotes: 1
Reputation: 23958
Array_intersect and Implode can do the job.
First find the 1's and then use the keys in array_intersect_key to return the days, then implode it.
$arr = array(
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
);
$week = "1001110";
$search_arr = str_split($week);
echo implode(", ", array_intersect_key($arr, array_intersect($search_arr, [1])));
//Monday, Thursday, Friday, Saturday
To get true/false if today is 1 then use in_array.
var_export(in_array(date("l"), array_intersect_key($arr, array_intersect($search_arr, [1]))));
//true because it's Saturday today
Upvotes: 1