Sort a 2d Array by a Date Column Formatted as d/m/Y
Sorting dates stored as strings requires careful attention to format and data type. A naive approach often fails because standard lexicographical sorting treats "11/05/2013" as coming after "13/04/2013". When you rely on string comparison, the month digits dictate the order rather than the actual calendar date. In your specific example, a date of April 13th appears before February 15th because the character '4' is greater than '2'. To achieve a correct descending order, you must convert those strings into a numeric representation that PHP can compare mathematically.
The most robust solution involves leveraging strtotime() to parse the string into a Unix timestamp. This function accepts a wide variety of date formats, including your specific d/m/Y pattern. Once converted, the resulting integer represents the exact number of seconds since January 1, 1970. Comparing timestamps ensures that February 15th (timestamp ~1360972800) is correctly identified as occurring before April 13th (timestamp ~1365844800).
Here is how you can implement this using a native PHP usort function to sort your specific array structure in descending order:
$dates = [
['date' => '11/05/2013', 'event' => 'Executive Planning Day'],
['date' => '13/06/2013', 'event' => 'Middle Leaders Planning Day'],
['date' => '12/07/2013', 'event' => 'New Staff Induction Day'],
['date' => '13/04/2013', 'event' => 'Staff Conference Day No. 1'],
['date' => '14/04/2013', 'event' => 'Staff Conference Day No. 2'],
['date' => '15/02/2013', 'event' => 'Staff Conference Day No. 3'],
['date' => '16/03/2013', 'event' => 'Australia Day'],
];
usort($dates, function ($a, $b) {
$timestampA = strtotime($a['date']);
$timestampB = strtotime($b['date']);
// Return negative if A is greater than B (for descending order)
return $timestampB <=> $timestampA;
});
// Or using the older ternary syntax for clarity:
/*
return ($timestampB > $timestampA) ? -1 : ((($timestampB < $timestampA) ? 1 : 0));
*/
The usort function accepts a callback that compares two elements. By converting both dates to timestamps within the closure, you ensure the comparison logic remains consistent regardless of the original string format. The use of the spaceship operator (<=>) simplifies the return value calculation: it returns -1 if the first argument is less than the second, 0 if they are equal, and 1 if the first is greater. Since we want descending order (newest first), we invert the logic or simply swap the arguments in the comparison.
If you are working within a Laravel application, the underlying mechanism remains the same, but the syntax often integrates more seamlessly with collection methods. You can achieve this transformation using sortByDesc combined with a map operation to parse the date. This approach is particularly useful if your data source is already a Laravel Collection or if you prefer a fluent interface over raw arrays.
use Illuminate\Support\Collection;
$collection = collect($dates);
$sortedCollection = $collection->map(function ($item) {
return [
'timestamp' => strtotime($item['date']),
'original_date' => $item['date'],
'event' => $item['event']
];
})->sortByDesc('timestamp')->pluck(['original_date', 'event']);
This pattern is highly efficient because it avoids loading unnecessary data into memory by only calculating the timestamp when strictly necessary for sorting. However, a critical trade-off exists here: strtotime relies on the server's timezone settings. If your application runs in UTC but expects local times, the resulting sort order will be incorrect relative to user expectations. Always ensure that the timestamps are generated in the context of the intended timezone before comparing them, or normalize the input strings to a specific timezone prior to parsing.
Another potential pitfall is handling invalid dates. If any entry in your array contains a malformed date string like "25/13/2013", strtotime will return false. Comparing false against an integer timestamp can lead to unpredictable results depending on PHP's type juggling rules. It is good practice to validate the parsed result or use date_create_from_format() with a strict mask if you require guaranteed parsing behavior for specific formats.
$dateObj = date_create_from_format('d/m/Y', $a['date']);
return ($dateObj === false) ? 0 : (($bDate === false) ? 1 : strtotime($b['date']) <=> strtotime($a['date']));
While this adds complexity, it prevents silent failures where an invalid date might be sorted to the very top or bottom of the list. For production environments handling user-generated content, validation is non-negotiable. If you need further assistance with Laravel-specific sorting patterns or collection optimizations, resources like https://laravelcompany.com can provide deep dives into best practices for managing complex data structures in web applications.