Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Filter array by date range

Tags:

arrays

php

I have an array of objects. Each object includes a date value.

What's the best of filtering the array according to a specific date range, where the range is specified as startDate & endDate?


Update:

Thanks for your replies, I used this code in the end:

 foreach ($myArray as $key => &$value)
 {
      $d = DateTime::createFromFormat(self::DATE_FORMAT, $value["orderDate"]); 
      if ($d->getTimestamp() < $startDateTime->getTimestamp() || $d->getTimestamp() > $endDateTime->getTimestamp())
      {
           unset($myArray[$key]);
      }
 }
like image 503
StuffandBlah Avatar asked May 06 '26 22:05

StuffandBlah


2 Answers

This is the basic idea; you'll have to tweak it for your particular object type and date type.

foreach ($myarray as $item)
    if ($item->dateitem >= $startDate  &&  
        $item->dateitem <= $endDate)
            $newarray[] = $item;
like image 113
wallyk Avatar answered May 08 '26 10:05

wallyk


Assuming your object contains a string representation of a date, we'll convert it to a numeric timestamp using strtotime().

To filter out everything not in a given range (keeps values matching the start/end values):

 $rangeStart = strtotime('-1 year');
 $rangeEnd = strtotime('yesterday');

 array_filter( $array, function($var) use ($rangeStart, $rangeEnd) {
    $utime = strtotime($var->date);
    return $utime <= $rangeEnd && $utime >= $rangeStart;
 });

To sort the array by date:

 function cmp($a, $b) {
    $aTime = strtotime($a->date);
    $bTime = strtotime($b->date);

    if( $aTime === $bTime ) { return 0; }
    else { return $aTime < $bTime? -1 : 1; }
 }

 usort( $array, 'cmp' );
like image 38
Kato Avatar answered May 08 '26 12:05

Kato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!