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.
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:
Array (  => 2016-09-12  => 2009-09-09  => 2009-09-06 )