DEV Community

xichlo
xichlo

Posted on

Determine Whether Two Date Ranges Overlap in PHP

An interval is represented as a combination of start time and end time. Given a set of intervals, check if any two intervals intersect.

Examples:

$periods = [
   ['start_time' => "09:00", 'end_time' => '10:30'],
   ['start_time' => "14:30", "end_time" => "16:30"],
   ['start_time' => "11:30", "end_time" => "13:00"],
   ['start_time' => "10:00", "end_time" => "11:30"]
];
Enter fullscreen mode Exit fullscreen mode

Expected time complexity is O(nLogn) where n is number of intervals.

/**
 * Check the two time periods overlap
 *
 * Example:
 * $periods = [
 *      ['start_time' => "09:00", 'end_time' => '10:30'],
 *      ['start_time' => "14:30", "end_time" => "16:30"],
 *      ['start_time' => "11:30", "end_time" => "13:00"],
 *      ['start_time' => "10:30", "end_time" => "11:30"],
 * ]
 *
 * @param $periods
 * @param string $start_time_key
 * @param string $end_time_key
 * @return bool
 */
public static function isOverlapped($periods, $start_time_key = 'start_time', $end_time_key = 'end_time')
{
    // order periods by start_time
    usort($periods, function ($a, $b) use ($start_time_key, $end_time_key) {
        return strtotime($a[$start_time_key]) <=> strtotime($b[$end_time_key]);
    });
    // check two periods overlap
    foreach ($periods as $key => $period) {
        if ($key != 0) {
            if (strtotime($period[$start_time_key]) < strtotime($periods[$key - 1][$end_time_key])) {
                return true;
            }
        }
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode

In this script, i use <=> Spaceship operator, you can check it here

Copy from Zeroblog

Top comments (0)