2

I have array

Array
(
    [0] => 2016-02-22 00:20:00
    [1] => 2016-02-25 08:45:00
    [2] => 2016-02-25 19:10:00
    [3] => 2016-02-25 20:00:00
    [4] => 2016-02-26 15:55:00
    [5] => 2016-02-28 17:10:00
)

How can i find which is nearest date from current date?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Artyom Kondra
  • 105
  • 1
  • 8

2 Answers2

2
//Start with your array
$array = ["2016-02-22 00:20:00", "2016-02-25 08:45:00", "2016-02-25 19:10:00", "2016-02-25 20:00:00", "2016-02-26 15:55:00", "2016-02-28 17:10:00", "2016-01-22 00:00:00"];

//Set an array called $closestTime that has the time difference and the key
$closestTime = [null,null];

//Check each element in array
foreach($array as $key => $date){

    //Calculate difference between now and the time in seconds
    $diff = strtotime("now") - strtotime($date);;
    if($diff<0) $diff = $diff * -1; 

    //If $closestTime is empty, populate it
    if($closestTime[0]===null) $closestTime = [$diff,$key];

    //If $closestTime isn't empty and the current date's time difference
    //is smaller, populate $closestTime with the time difference and key
    elseif($diff < $closestTime[0]) $closestTime = [$diff,$key];
}

//Print the closest time
echo $array[$closestTime[1]];

//Outputs:
//2016-02-26 15:55:00
Ben
  • 8,894
  • 7
  • 44
  • 80
1

Easy: transform to timestamps, subtract the searched timestamp and take absolute value, find minimum.

Fast, assuming sorted array of timestamps: use binary search to find the first element that is larger, compare distance to that element with distance to previous element, pick one with smaller distance; if no element is larger, pick last element; if first element is already larger, pick first element.

Amadan
  • 191,408
  • 23
  • 240
  • 301