How to Sort a Multi-dimensional Array by Date in Ascending order in PHP

PHP usort() function provides an easy way to sort an array by values. The usort() method can be used to sort an associative array by specific key-value using PHP. In this example, we will show you how to sort a multi-dimensional array by data in PHP.

The following code snippet help to sort an array by data value in ascending order in PHP.

  • The strtotime() function is used to convert data to timestamp with 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'
);

usort($events_arr, function($a$b) {
  return 
strtotime($a['date']) - strtotime($b['date']);
});

RELATED HOW TO GUIDES

Leave a reply

keyboard_double_arrow_up