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 )
- How to sort an array of dates in C/C++?
- Return all dates between two dates in an array in PHP
- C++ program for Sorting Dates using Selection Sort
- Comparing two dates in PHP
- Comparing dates in Python
- How to calculate the difference between two dates in PHP?
- PHP | Number of week days between two dates
- Find number of days between two given dates
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.