Skip to content
Advertisement

How to sort an array of dates by PHP?

I am using the array_push and array_unshift methods but when I order it, it combines the 12-2020 in the year 2021, here is an example.

JavaScript

As you can see, the ones from December 2020 are at the end, but they should be at the beginning and before 01-2021.

Advertisement

Answer

You could do this using usort on your array of date strings. You would compare them e.g. with strotime($a) <=> strtotime($b), or array_reverse(explode('-', $a)) <=> ... $b on all dates. However, this approach would quickly become a very expensive operation, given the cartesian(?) amount of conversions that would be made when each item is compared, unless the conversions were somehow cached. I wouldn’t go down this path here.

In general, it’s better to sort your data when the data is still in a more readily comparable format, where at all possible. I don’t think you can just usort Carbon objects though (without some overhead, as above, anyway!), so here’s a no-frills solution that performs well.

Assuming the array keys hold no particular meaning for you, you can generate timestamps for keys. You can then scrap all the unshift/push logic, and simply do something like this:

JavaScript

This will give you an array (here, $times) of date strings with timestamp-indexes. (Adapt the variables to fit your case.) Then it’s as trivial as applying ksort($times) to the resulting array, ie. sorting the array by key. Your date strings will be in chronological order.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement