Remove dates in the past in php array?-ThrowExceptions

Exception or error:

Struggling to get my head around this…

$dates_list outputs this array

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [event_date] => 2020-11-19 00:00:00
                    [event_start_time] => 13:07:00
                    [event_end_time] => 17:07:00
                )

            [1] => Array
                (
                    [event_date] => 2020-06-17 00:00:00
                    [event_start_time] => 10:07:00
                    [event_end_time] => 17:07:00
                )

            [2] => Array
                (
                    [event_date] => 2020-03-05 00:00:00
                    [event_start_time] => 15:46:00
                    [event_end_time] => 20:46:00
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [event_date] => 2020-07-07 00:00:00
                    [event_start_time] => 20:10:00
                    [event_end_time] => 20:10:00
                )

            [1] => Array
                (
                    [event_date] => 2020-03-13 00:00:00
                    [event_start_time] => 20:10:00
                    [event_end_time] => 20:10:00
                )

        )

)

I’ve created $now which shows the current date and time

$now = date("Y-m-d h:i:s");
// 2020-03-12 09:17:42

@RoboRobok provided this answer, it worked when the array wasn’t nested

$dates_filtered = array_filter($dates_list,
            function ($date_entry) use ($now) {
                return $date_entry['event_date'] >= $now;
            }
        );

How can I access the nested arrays to remove past days from the array?

How to solve:

Use array_filter:

$result = array_filter(
    $dates_list,
    function ($date_entry) use ($now) {
        $date = substr($date_entry['event_date'], 0, 10);
        $time = $date_entry['event_start_time'];

        return "$date $time" >= $now;
    }
);

Answer´╝Ü

Try this

foreach($dates_list as $i=>$dateItem){
   if (strtotime($dateItem['event_date']) < time()) {
    // past date
    unset($dates_list[$i]);
}

}
print_r($dates_list);

Leave a Reply

Your email address will not be published. Required fields are marked *