- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort an array of dates in PHP
To sort an array of dates in PHP, the code is as follows−
Example
<?php function compareDates($date1, $date2){ return strtotime($date1) - strtotime($date2); } $dateArr = array("2019-11-11", "2019-10-10","2019-08-10", "2019-09-08"); usort($dateArr, "compareDates"); print_r($dateArr); ?>
Output
This will produce the following output−
Array ( [0] => 2019-08-10 [1] => 2019-09-08 [2] => 2019-10-10 [3] => 2019-11-11 )
Example
Let us now see another example −
<?php function compareDates($date1, $date2){ if (strtotime($date1) < strtotime($date2)) return 1; else if (strtotime($date1) > strtotime($date2)) return -1; else return 0; } $dateArr = array("2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11", "2019-01-01"); usort($dateArr, "compareDates"); print_r($dateArr); ?>
Output
This will produce the following output−
Array ( [0] => 2019-11-11 [1] => 2019-11-11 [2] => 2019-10-10 [3] => 2019-09-08 [4] => 2019-05-11 [5] => 2019-01-01 )
Advertisements