Given two weekdays: Monday, Wednesday.
How do you get the intermediate days in that array? Answer: Monday, Tuesday, Wednesday.
Case 2: from Monday to Monday Answer: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Monday
Thanks!
Given two weekdays: Monday, Wednesday.
How do you get the intermediate days in that array? Answer: Monday, Tuesday, Wednesday.
Case 2: from Monday to Monday Answer: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Monday
Thanks!
My solution is more about moving the internal pointer of the array until the margins are found and pushing the elements between margins into another result array. Can be used regardless of what data is in the initial array.
function getDaysInBetween($start, $end)
{
$weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
$start_found = false;
$days = [];
while(true) {
$next = next($weekdays);
$day = (empty($day) || !$next)?reset($weekdays):$next;
if($day === $start) $start_found = true;
if($start_found) {
$days[] = $day;
if($day===$end && count($days)>1) return implode(", ",$days);
}
}
}
Live demo here: https://3v4l.org/D5063
I've created this function which does this, and the comments step you through how it was done.
function list_days($start, $end) {
//convert day "word" to it's given number
//Monday = 1, Tuesday = 2 ... Sunday = 7
$start_n = date('N', strtotime($start));
$end_n = $end_range = date('N', strtotime($end));
//we also set $end_range above, by default it's set to the $end day number,
//but if $start and $end are the same it will be changed later.
//create an empty output array
$output = [];
//determine end_range for the for loop
//if $start and $end are not the same, the $end_range is simply the number of $end (set earlier)
if($start_n == $end_n) {
//if $start and $end ARE the same, we know there is always 7 days between the days
//So we just add 7 to the start day number.
$end_range = $start_n + 7;
}
//loop through, generate a list of days
for ($x = $start_n; $x <= $end_range; $x++) {
//convert day number back to the readable text, and put it in the output array
$output[] = date('l', strtotime("Sunday +{$x} days"));
}
//return a string with commas separating the words.
return implode(', ', $output);
}
Usage:
Example 1:
echo list_days('Monday', 'Wednesday');
//output: Monday, Tuesday, Wednesday
Example 2:
echo list_days('Monday', 'Monday');
//output: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Monday