Sort an array of dates in PHP

PHPServer Side ProgrammingProgramming

To sort an array of dates in PHP, the code is as follows−

Example

 Live Demo

<?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 −

 Live Demo

<?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
)
raja
Published on 26-Dec-2019 12:17:56
Advertisements