Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to sort dates given in the form of an array
To sort dates given in the form of an array in PHP, you can use the usort() function with a custom comparison function. This approach leverages strtotime() to convert date strings into timestamps for accurate comparison.
Example
<?php
function compare_dates($time_1, $time_2)
{
if (strtotime($time_1) > strtotime($time_2))
return -1;
else if (strtotime($time_1) < strtotime($time_2))
return 1;
else
return 0;
}
$my_arr = array("2020-09-23", "2090-12-06", "2002-09-11", "2009-11-30");
usort($my_arr, "compare_dates");
print_r("The dates in sorted order: ");
print_r($my_arr);
?>
Output
The dates in sorted order: Array
(
[0] => 2090-12-06
[1] => 2020-09-23
[2] => 2009-11-30
[3] => 2002-09-11
)
How It Works
The function compare_dates takes two date parameters and uses strtotime() to convert them into Unix timestamps. It returns −1 if the first date is greater (for descending order), 1 if the second date is greater, and 0 if they are equal. The usort() function applies this custom comparison to sort the array in descending order (newest to oldest).
Ascending Order Example
<?php
function compare_dates_asc($time_1, $time_2)
{
return strtotime($time_1) - strtotime($time_2);
}
$dates = array("2020-09-23", "2090-12-06", "2002-09-11", "2009-11-30");
usort($dates, "compare_dates_asc");
print_r($dates);
?>
Conclusion
Use usort() with strtotime() for reliable date sorting. Return negative values for descending order or use subtraction for ascending order in your comparison function.
