Search code examples
phparraysdatetimedifferencephp-carbon

PHP get closest time to given array of times


I have an array called $timeslots with timeslots like:

array:32 [▼
  0 => "2018-12-15T12:00:00.0000000"
  1 => "2018-12-15T12:15:00.0000000"
  2 => "2018-12-15T12:30:00.0000000"
  3 => "2018-12-15T12:45:00.0000000"
  4 => "2018-12-15T13:00:00.0000000"
  5 => "2018-12-15T13:15:00.0000000"
  6 => "2018-12-15T13:45:00.0000000"
  7 => "2018-12-15T14:15:00.0000000"
  8 => "2018-12-15T14:30:00.0000000"
  9 => "2018-12-15T14:45:00.0000000"
  10 => "2018-12-15T15:00:00.0000000"
  11 => "2018-12-15T15:15:00.0000000"
  12 => "2018-12-15T15:30:00.0000000"
  13 => "2018-12-15T15:45:00.0000000"
  14 => "2018-12-15T16:15:00.0000000"
  15 => "2018-12-15T16:45:00.0000000"
  16 => "2018-12-15T17:00:00.0000000"
  17 => "2018-12-15T17:30:00.0000000"
  18 => "2018-12-15T17:45:00.0000000"
  19 => "2018-12-15T18:30:00.0000000"
  20 => "2018-12-15T18:45:00.0000000"
  21 => "2018-12-15T19:15:00.0000000"
  22 => "2018-12-15T19:45:00.0000000"
  23 => "2018-12-15T20:15:00.0000000"
  24 => "2018-12-15T20:45:00.0000000"
  25 => "2018-12-15T21:00:00.0000000"
  26 => "2018-12-15T21:15:00.0000000"
  27 => "2018-12-15T21:30:00.0000000"
  28 => "2018-12-15T21:45:00.0000000"
  29 => "2018-12-15T22:00:00.0000000"
  30 => "2018-12-15T22:15:00.0000000"
  31 => "2018-12-15T22:30:00.0000000"
]

Also, I have a variable like:

$expected_time = 2018-12-15T18:00:00.0000000; // this can be different value, so its not unique value

$expected_time is never into array $timeslots but I need to find closest value to $expected_time... How I can do that?

How I can get the closest timeslot value from array $timeslots to $expected_time and calculate the difference in minutes?

Any idea?


Solution

  • As Nico mentioned in the comments, it's pretty straightforward. Just looping and calculating the time difference.

    $timeslots = [...];
    $expected_time = "2018-12-15T18:00:00.0000000";
    $timestamp = strtotime($expected_time);
    $diff = null;
    $index = null;
    
    foreach ($timeslots as $key => $time) {
        $currDiff = abs($timestamp - strtotime($time));
        if (is_null($diff) || $currDiff < $diff) {
            $index = $key;
            $diff = $currDiff;
        }
    }
    
    echo $timeslots[$index];