How to Filter Array by Date Range in PHP

The foreach loop can be used to filter array in PHP. But, the execution time is high to filter elements from a multidimensional array with PHP foreach. PHP array_filter() function is the best alternative to filter array by specific condition (key=value). You can use the array_filter() function to filter multidimensional array by date range using PHP. This example will show you how to filter array by specific date range in PHP.

The following code snippet helps to filter last month events from an array using the array_filter() and strtotime() function in PHP.

$events_arr = array(  
    array(
'title' => 'Event 1''date' => '2022-02-25'), 
    array(
'title' => 'Event 2''date' => '2022-02-21'), 
    array(
'title' => 'Event 3''date' => '2022-02-15'), 
    array(
'title' => 'Event 4''date' => '2022-01-22'), 
    array(
'title' => 'Event 5''date' => '2022-01-18'
); 
 
$rangeStart strtotime('-1 month'); 
$rangeEnd strtotime('yesterday'); 
 
$filtered_events array_filter($events_arr, function($var) use ($rangeStart$rangeEnd) { 
    
$evtime strtotime($var['date']); 
    return 
$evtime <= $rangeEnd && $evtime >= $rangeStart
});

If you want to use a specific date range, pass the date in strtotime() function in PHP.

$rangeStart strtotime("2022-02-22"); 
$rangeEnd strtotime("2022-02-28");

Leave a reply

keyboard_double_arrow_up