Wednesday, 13 September 2017

How to get closest date compared to an array of dates in PHP

Here Explain about how to find nearest date from any array of dates
Let's say I have an array as follows:

Array
(
    [0] => 2017-09-14
    [1] => 2017-09-15
    [2] => 2017-09-16
    [3] => 2017-09-17
    [4] => 2017-09-18
    [5] => 2017-09-19
)

I want to find 2017-09-16th closest date it must be less than from that date.
 Public function findClosestDate($dates_array, $fordate){
    $mostRecent= 0;
      foreach($dates_array as $date){
        $curDate = $date;
        if ($curDate >= $mostRecent && $curDate <= $fordate) {
         $mostRecent = $curDate;
         }
      }
    return $mostRecent;
  }
It will return 2017-09-15.

No comments:

Post a Comment