Sort an array of dates in PHP
Last Updated :
01 Jul, 2024
Improve
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:
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
- strtotime() : This function changes a given date string into timestamp (large int value).
- usort() : This function sorts the given array as per a user defined comparison function.
Below is the PHP implementation of above idea:
<?php
// PHP program to sort array of dates
// user-defined comparison function
// based on timestamp
function compareByTimeStamp($time1, $time2)
{
if (strtotime($time1) < strtotime($time2)) {
return 1;
} elseif (strtotime($time1) > 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
// Sample array of dates
$dates = ["2023-05-15", "2022-11-20", "2024-03-10", "2023-01-05"];
// Function to convert date to a sortable format
$convertDate = function ($date) {
return date("Y-m-d", strtotime($date));
// Use alternative method if strtotime() is not allowed
};
// Convert dates using the function
$sortableDates = array_map($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 )