We’ve seen plenty of bad dates, but as always, there are new ways to be surprised by the bizarre inventions people come up with. Today, Team it sends us bad date sorting in PHP.
function cmp($a, $b)
return strcmp(strtotime($a["date"]), strtotime($b["date"]));
usort($data, "cmp");
The cmp
function resides in the global namespace, which is a good way to ensure future confusion – it has a very specific job, but has a very generic name. And the work he does is… an interesting approach.
The “date” field in our records is a string. It is a string formatted in YYYY-MM-DD HH:MM:SS
, and this is the input guarantee – which we’ll get to in a moment. So the first thing to notice is that arrays can already be sorted and nothing about this function needs to exist.
But being useless is not the end. We convert the string time to a Unix timestamp using strtotime
, which gives us an integer – also trivially sortable. But then we get over it strcmp
which converts an integer back to a string, so we can do a string comparison on it.
Elsewhere in the code we use usort
passing that wonderfully named $data
variable and then application cmp
to sort it out.
Unrelated to this code, but a PHP quirk, we pass the callable cmp
as a string on usort
function to apply sorting. Every time I write an article about PHP, I learn a new horror of the language, and “strings as callable objects” is definitely terrifying.
Now, I said a moment ago that we know the input format. That’s a bold claim, especially for such a generically named function, but it’s important: this function is used to sort the results of database queries. It is as we know the date format – the input comes directly from the query.
A query that could easy to modify include an ORDER BY
clause, rendering this whole thing useless.
and actually someone made that change in the querywhich means that the data is already sorted before being passed to usort
function, which performed its own heaps of transformations to sort it back into the same order.
Otter – Secure your servers automatically without the need to log into the command line. Get started today!