Open In App

Sort an array of dates in PHP

Last Updated : 08 Mar, 2018
Like Article

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 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;
        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");

Output :

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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads