Created
October 21, 2012 17:46
-
-
Save mrw4n/3927804 to your computer and use it in GitHub Desktop.
PHP Function to show week days range from a given array of week days
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function show_days($days = array()) { | |
$days_array = array( | |
1 => 'Saturday', | |
2 => 'Sunday', | |
3 => 'Monday', | |
4 => 'Tuesday', | |
5 => 'Wednesday', | |
6 => 'Thursday', | |
7 => 'Friday', | |
); | |
$possibilities = array(); | |
foreach ($days as $key => $value) { | |
$possibilities[$value][] = intval($value); | |
for ($i = $value + 1; $i != $value; $i++) { | |
if ($i == 8 && $value == 7) | |
$i = 1; | |
if (!in_array($i, $days)) { | |
break; | |
} | |
$possibilities[$value][] = $i; | |
if ($i == 7) | |
$i = 0; | |
} | |
} | |
foreach ($possibilities as $key => $value) { | |
foreach ($possibilities as $key_inner => $value_inner) { | |
if ($key == $key_inner) { | |
continue; | |
} | |
if (in_array($key, $value_inner)) { | |
unset($possibilities[$key]); | |
} | |
} | |
} | |
$return = array(); | |
foreach ($possibilities as $key => $value) { | |
$count = count($value); | |
if ($count == 1) { | |
$return[] = $days_array[$value[0]]; | |
} | |
elseif ($count == 2) { | |
$return[] = str_replace(array_keys($days_array), $days_array, implode(', ', $value)); | |
} | |
elseif ($count == 7) { | |
$return[] = 'Everyday'; | |
} else { | |
$value = array_values($value); | |
$first = array_shift($value); | |
$last = array_pop($value); | |
$return[] = str_replace(array_keys($days_array), $days_array, $first . ' to ' . $last); | |
} | |
} | |
return implode(' And ', $return); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment