Friday, October 24, 2025
HomeLanguagesSort an array of dates in PHP

Sort an array of dates in PHP

We are given an array which consists of multiple dates in (Y-m-d) format. We have to write a program in PHP to sort all the dates present 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

To solve this problem in C/C++/Java or any other general purpose programming language we have to either compare dates based on year then month and finally according to days either by storing them in any structure or any other desired data structure. But in PHP this problem seems to be very easy if we apply strtotime() function. The strtotime() function is a PHP function which changes a given date in any format into a timestamp which is a large integer in nature and then while sorting the array we can easily use the 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;
    else if (strtotime($time1) > strtotime($time2)) 
        return -1;
    else
        return 0;
}
  
// Input Array
$arr = array("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
)
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS