3v4l.org

run code in 300+ PHP versions simultaneously
<?php date_default_timezone_set('UTC'); $dates = array( '2014-01-20 20:00:00', '2014-01-21 20:00:00', '2014-01-22 14:00:00', '2014-01-22 20:00:00', '2014-01-23 20:00:00', '2014-01-25 20:00:00', '2014-01-26 20:00:00', '2014-01-31 20:00:00', '2014-02-01 20:00:00' ); function getDateRanges($dates) { $tsArr = array_map('strtotime', $dates); $ranges = array(); for ($i=0, $len = count($tsArr); $i < $len; $i++) { $rstart = $tsArr[$i]; $rend = $rstart; // determine the end of the range while (isset($tsArr[$i+1]) && ($tsArr[$i+1]-$tsArr[$i]) / (60*60) <= 24) { $rend = $tsArr[++$i]; } // create DateTime objects to work with dates $startDate = new DateTime('@'.$rstart); $endDate = new DateTime('@'.$rend); // get date start and last day of month $start = $startDate->format('j'); $lastDay = $startDate->format('t'); // if last day of month, append month name if ($start == $lastDay) $start = $startDate->format('jS M'); else $start = $startDate->format('jS'); // end date $end = $endDate->format('jS M ga'); $ranges[] = $start.'-'.$end; } return $ranges; } $arr = getDateRanges($dates); echo implode(', ', $arr);

preferences:
53.95 ms | 402 KiB | 5 Q