PHP: How to sort an array of dates and times?
Table of contents
In PHP it is very easy to sort an array of dates and times. All you need to do is convert it to a (integer) timestamp, and then do a normal sort. Here are more details:
First, convert the dates into a timestamp
A timestamp is time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). The current timestamp (when this page was last cached, anyway) is: 1550289609 (time()
).
Because there is no standard PHP array function for sorting date strings we will have to convert it ourselves. But we can make a closure, and pass that to usort(&$array, $compare_func)
(which lets us define our own function to do the comparisons for the sorting)
The custom comparison function for usort
takes 2 parameters. It returns either -1, 0, or 1 depending on how they compare (1 if $a is less than $b; -1 if $a is greater than $b; 0 if equal). We can use PHP's spaceship operator for this (<=>) .
Let's set up the data:
- $dates = [
-
- "10 September 2000",
- "10 September 2020",
- "9 September 2020",
- "9 September 2000",
- "5 April 1999",
- "20 April 1998",
- ];
And now the comparison function:
- $compare_function = function($a,$b) {
-
- $a_timestamp = strtotime($a); // convert a (string) date/time to a (int) timestamp
- $b_timestamp = strtotime($b);
-
- // new feature in php 7
- return $a_timestamp <=> $b_timestamp;
-
- /* old way to do it:
-
- if ($a_timestamp > $b_timestamp) {
- return -1;
- }
- elseif ($a_timestamp < $b_timestamp) {
- return 1;
- }
- else {
- return 0;
- }
-
- */
-
- };
Now we have everything we need - let's sort that data!
- usort($dates, $compare_function);
- var_dump($dates);
array:6 [ 0 => "20 April 1998" 1 => "5 April 1999" 2 => "9 September 2000" 3 => "10 September 2000" 4 => "9 September 2020" 5 => "10 September 2020" ]
More...
Comments and discussion about How to sort an array of dates and times?
Found this interesting? Maybe you want to read some more in this series?
Or see other topics in the PHP language
Arrays
General
PHP Basics
Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScriptOr see random questions
What does 'final class' and 'final function' (final method) mean in PHP?
How to namespace a Laravel route group?
How to remove .php from the end of URLs with .htaccess
How to install and use optipng on Linux CentOS
An overview of every main PHP array function
How to access the Laravel's route parameters outside of the controller?
How to manually write your own pagination in PHP
How to get table column names from a database table in Eloquent?
How to find the index of a value in an array in JS?
How to group a SQL statement in brackets/parenthesis