Sort an array of dates in PHP (original) (raw)

Last Updated : 01 Jul, 2024

We are given an array of multiple dates in (Y-m-d) format. We have to write a program in PHP to sort all the dates in the array in decreasing order. Examples :

Input : array("2018-06-04", "2014-06-08", "2018-06-05") Output : 2018-06-05 2018-06-04 2014-06-08

Input : array("2016-09-12", "2009-09-08", "2009-09-09") Output : 2016-09-12 2009-09-09 2009-09-08

Here we have some common methods:

Table of Content

PHP usort() function

by defining a comparator function. The comparator function will accept two date arguments which will be converted to integer timestamp using strtotime() function and then compared to sort date based on integer timestamp value.

**Inbuilt Functions used

Below is the PHP implementation of above idea:

PHP `

strtotime($time2)) { return -1; } else { return 0; } } // Input Array $arr = ["2016-09-12", "2009-09-06", "2009-09-09"]; // sort array with given user-defined function usort($arr, "compareByTimeStamp"); print_r($arr); ?>

`

Output :

Array ( [0] => 2016-09-12 [1] => 2009-09-09 [2] => 2009-09-06 )

Using array_multisort() with Custom Date Conversion

Sort an array of dates in PHP by converting them to a sortable format using array_map(), then utilize array_multisort() on the converted dates to achieve chronological order

**Example:

PHP `

convertDate=function(convertDate = function (convertDate=function(date) { return date("Y-m-d", strtotime($date)); // Use alternative method if strtotime() is not allowed }; // Convert dates using the function sortableDates=arraymap(sortableDates = array_map(sortableDates=arraymap(convertDate, $dates); // Sort the array of dates maintaining index association array_multisort($sortableDates, SORT_ASC, $dates); // Print the sorted dates print_r($dates); ?>

`

Output

Array ( [0] => 2022-11-20 [1] => 2023-01-05 [2] => 2023-05-15 [3] => 2024-03-10 )