Test if a range intersects another range of numbers

前端 未结 6 1433
小鲜肉
小鲜肉 2021-01-07 03:41

I have 2 range of numbers:

  • $startTime to $endTime
  • $offerStartTime to $offerEndTime

6条回答
  •  旧时难觅i
    2021-01-07 04:12

    You can use range and array_intersect, i.e.:

    function time_intersect($startTime, $endTime, $offerStartTime, $offerEndTime)
    {
        $start_to_end = range($startTime, $endTime, 1);
        $offer_start_end = range($offerStartTime, $offerEndTime, 1);
        if (!empty(array_intersect($start_to_end, $offer_start_end)))
        {
          # time overlaps
          return true;
        }
    }
    

    Explanation:

    With range we create 2 arrays containing numbers based on the 4 variables (start, end), then we use array_intersect to check if the 2 arrays have numbers in common, if the output is not empty, we know the numbers (time) overlap.

提交回复
热议问题