Possible Duplicate:
Check for consecutive dates within a set and return as range
I have an array of dates which is obtained from a mySQL query. I need to divide the array into multiple arrays so that the dates in each array are contiguous.
So, if I start with
$datearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08", "2013-06-19", "2013-06-20", "2013-06-21");
I need to be able to split that into
$firstdatearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08");
$seconddatearray = array("2013-06-29", "2013-06-30", "2013-07-01");
Finally I will be able to print
5 - 8 Mar, 29 Jun - 1 Jul
How can I do that? I haven't a clue where to start.
THIS IS THE COMPLETE WORKING ANSWER. (Enjoy!)
You'll have to loop through each value in $datearray
<?php
$datearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08", "2013-06-19", "2013-06-20", "2013-06-21");
asort($datearray);
$resultArray = array();
$index = -1;
$last = 0;
$out = "";
foreach ($datearray as $date) {
    $ts = strtotime($date);
    if (false !== $ts) {
        $diff = $ts - $last;
        if ($diff > 86400) {
            $index = $index + 1;
            $resultArray[$index][] = $date;
        } elseif ($diff > 0) {
            $resultArray[$index][] = $date;
        } else {
            // Error! dates are not in order from small to large
        }
        $last = $ts;
    }
}
foreach ($resultArray as $a) {
    if (count($a) > 1) {
        $firstDate = $a[0];
        $firstDateBits = explode('-',$firstDate);
        $lastDate = $a[count($a)-1];
        $lastDateBits = explode('-',$lastDate);
        if ($firstDateBits[1] === $lastDateBits[1]) {
            $out .= intval($firstDateBits[2]) . '-' . intval($lastDateBits[2]) . ' ' . date("M",strtotime($firstDate)) . ', ';  
        } else {
            $out .= date("M d",strtotime($firstDate)) . '-' . date("M d",strtotime($lastDate)) . ', ';  
        }
    }
}
This is the output:
5-8 May, 19-21 Jun
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With