DEV Community

xichlo
xichlo

Posted on

4 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay