Sorting PHP Arrays by Date Strings
You have an array of associative arrays where each element contains a title and a date. The date is currently stored as a string in RFC 2822 format, such as "Fri, 17 Jun 2011 08:55:57 +0200". You want to sort the items chronologically.
The short answer is yes, you can absolutely sort by a value that exists inside every item. However, PHPâs default sorting functions do not know how to parse RFC 2822 strings directly for comparison. If you pass this array directly to usort() or uasort() without preprocessing, the function will treat the dates as plain text and sort them alphabetically.
For example, "Mon, 16 Jun 2010" would come before "Fri, 17 Jun 2011", which is correct in this specific case. But try sorting "Sep 15" against "Aug 30". Alphabetically, "Aug" comes before "Sep", so that works. However, if you have "2011-01-01" and "2011-01-02", they sort correctly. But RFC 2822 strings like "Fri, 17 Jun" rely on the full month name. While often sortable lexicographically because months are ordered A-Z and days are numeric with leading zeros in standard formats, relying on string comparison for dates is fragile. It breaks if you encounter "Oct" vs "Nov" (correct) but fails completely if your data includes non-standard formatting or lacks leading zeros on the day (e.g., "1 Jul" vs "2 Jul" sorts fine, but "9 Jul" vs "10 Jul" would sort incorrectly because '1' < '9').
To ensure robustness, you should convert these strings to Unix timestamps. This guarantees a numeric comparison regardless of the specific date format nuances.
Converting RFC 2822 to Timestamps
The date() function in PHP accepts an RFC 2822 string and returns the corresponding Unix timestamp. You can use array_walk or a loop to transform your array before sorting, or you can create a custom callback that converts on the fly if you prefer not to mutate the original data structure permanently.
Here is a practical approach using usort. We define a comparison function that converts both dates to timestamps and compares those integers:
$items = [
['title' => 'Another title', 'date' => 'Fri, 17 Jun 2011 08:55:57 +0200'],
['title' => 'My title', 'date' => 'Mon, 16 Jun 2010 06:55:57 +0200'],
];
usort($items, function ($a, $b) {
$timeA = strtotime($a['date']);
$timeB = strtotime($b['date']);
if ($timeA === $timeB) {
return 0;
}
return ($timeA < $timeB) ? -1 : 1;
});
// Result: "My title" (2010) comes before "Another title" (2011)
print_r($items);
In this example, strtotime() handles the RFC 2822 format perfectly. It returns an integer representing seconds since the Unix epoch. The comparison logic is now strictly numeric, eliminating any risk of lexicographical errors.
Trade-offs and Data Integrity
A common question is whether converting to a timestamp changes the original date string stored in the array. In the example above, we only calculate the timestamp within the closure; the $a['date'] and $b['date'] strings remain untouched. This allows you to keep your data model clean while leveraging the sorting engine's strength with integers.
If you need to persist this sorted order or use it elsewhere, you might choose to mutate the array by adding a timestamp key alongside the string:
array_walk($items, function (&$item) {
$item['timestamp'] = strtotime($item['date']);
});
usort($items, function ($a, $b) {
return $a['timestamp'] <=> $b['timestamp'];
});
This approach makes the sort key explicit and avoids recalculating the timestamp every time you compare two items. The space overhead is negligible for most applications, but it is a consideration for high-volume data processing where memory usage is tight.
Why Not Use the Date as an ID?
You mentioned not wanting to use the date as an ID because multiple items could share the same date. That intuition is spot on. Using a non-unique value as a sort key or database identifier leads to unpredictable behavior when duplicates exist. By converting to a timestamp, you preserve the uniqueness of the moment in time (down to the second), ensuring that even if two items have the same calendar date and time, they are treated distinctly in the sort order unless their timestamps are identical.
For modern PHP development, especially within frameworks like Laravel, this pattern is standard. If you are working with a collection of Eloquent models or generic arrays, sortBy helpers often expect comparable values. Ensuring your sort key is numeric via strtotime() or DateTime::createFromFormat() aligns with best practices for predictable data ordering.
