Finding missing consecutive dates in an PHP array

I have dates stored as ‘2008-01-01′ in the period field of a table. It’s the format Y-m=d. I needed a way to query the database and determine if the returned periods were broken consecutively or not. This is what I came up with to solve the problem. The query already returns ORDER BY period ASC so the values are in the right order for this to work. This had me stumped for a good bit.


    $periods = array('2007-11-01','2007-12-01','2008-02-01','2008-03-01','2008-04-01','2008-05-01','2008-06-01');
    for($i=0;$i<count ($periods);$i++){
        $d1 = strtotime($periods[$i]);
        $d2 = date(’Y-m-d’,strtotime(’+1 month’, $d1));
        if($d2 != $periods[$i+1]){
            $trueMaxPeriod =  date(’Y-m-d’,$d1);
            break;
        }
    }

I thank the Lord for this because it’s not even close to where my mind was going. Also, Google didn’t turn up much either. So if you have an array of date values and need to find is a value is missing in the series, try the above.

Leave a Reply


Creative Commons License
This work is licensed under a Creative Commons Attribution-NoDerivs 2.5 License.