Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a sequence of days

Tags:

date

php

days

Let's say I have these arrays of numbers which correspond to the days in a week (starting on Monday):

/* Monday - Sunday */
array(1, 2, 3, 4, 5, 6, 7)

/* Wednesday */
array(3)

/* Monday - Wednesday and Sunday */
array(1, 2, 3, 7)

/* Monday - Wednesday, Friday and Sunday */
array(1, 2, 3, 5, 7)

/* Monday - Wednesday and Friday - Sunday */
array(1, 2, 3, 5, 6, 7)

/* Wednesday and Sunday */
array(3, 7)

How could I effectively convert these arrays to the desired strings as shown in the C-style comments? Any help would be greatly appreciated.

like image 451
Willem-Aart Avatar asked Jul 19 '14 15:07

Willem-Aart


1 Answers

The following code should work:

<?php
// Create a function which will take the array as its argument
function describe_days($arr){
$days = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
// Begin with a blank string and keep adding data to it
$str = "";
// Loop through the values of the array but the keys will be important as well
foreach($arr as $key => $val){
// If it’s the first element of the array or ...
// an element which is not exactly 1 greater than its previous element ...
    if($key == 0 || $val != $arr[$key-1]+1){
        $str .= $days[$val-1]."-";
    }
// If it’s the last element of the array or ...
// an element which is not exactly 1 less than its next element ...
    if($key == sizeof($arr)-1){
        $str .= $days[$val-1];
    }
    else if($arr[$key+1] != $val+1){
        $str .= $days[$val-1]." and ";
    }
}
// Correct instances of repetition, if any
$str = preg_replace("/([A-Z][a-z]+)-\\1/", "\\1", $str);
// Replace all the "and"s with commas, except for the last one
$str = preg_replace("/ and/", ",", $str, substr_count($str, " and")-1);
return $str;
}

var_dump(describe_days(array(4, 5, 6)));      // Thursday-Saturday
var_dump(describe_days(array(2, 3, 4, 7)));   // Tuesday-Thursday and Sunday
var_dump(describe_days(array(3, 6)));         // Wednesday and Saturday
var_dump(describe_days(array(1, 3, 5, 6)));   // Monday, Wednesday and Friday-Saturday
?>
like image 128
Sharanya Dutta Avatar answered Nov 08 '22 21:11

Sharanya Dutta