Sort a 2d array by dynamic date keys formatted as jS F, Y

Sort a 2d array by dynamic date keys formatted as jS F, Y

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Sorting Arrays by Dynamic Date Keys: Handling Human-Readable vs. ISO Formats

Sorting arrays in PHP often trips developers up when the keys are strings that look like dates but aren't standard ISO formats. Consider an array fetched from a legacy database or constructed dynamically where keys follow the pattern "28th February, 2009". Attempting to sort these using ksort() results in alphabetical ordering rather than chronological sorting because string comparison evaluates character by character ('2' vs 'F').

When your data arrives in standard MySQL date formats like '2008-02-28', the solution is straightforward. You can leverage PHP's built-in capabilities to treat these strings as sortable integers or dates. However, when you have hybrid structures—like an associative array containing both a human-readable key and a raw database string—you need a strategy that avoids inefficient nested loops while ensuring correctness.

The Trap of String Sorting

The most common mistake is assuming that sorting by keys automatically sorts by date. In PHP, ksort() performs a lexicographical sort. For keys like '2008-02-28' and '2009-10-05', this actually works because the year appears first in the string, followed by month and day. If you strictly rely on the ISO format (Y-m-d), ksort() is often sufficient without any custom logic.

However, if your keys are formatted as '28th February, 2009', lexicographical sorting fails immediately. A key starting with '2' might incorrectly appear before a key starting with '1' depending on the month name length, or worse, "January" sorts before "February" even if the years differ in a way that shouldn't happen. Relying on array_multisort with string keys formatted this way is unreliable because you must convert every single key into a comparable integer or timestamp before sorting.

The Efficient Solution: Extract and Sort Indices

Your suggestion of looping through the data to remove hyphens, converting to integers, sorting, and then looping back creates unnecessary overhead, especially when processing data per user. This approach forces three separate passes over the dataset, which hurts performance as the array grows.

A more robust method involves extracting the sortable integer component directly from the existing data structure without disrupting the original values. If you have a hybrid associative array where one key holds the human-readable date and another holds the raw database string (e.g., '20080228'), you can sort based on the numeric representation of that second element.

Here is how to handle the hybrid case efficiently:

$data = [
    ['human' => '28 Feb, 2009', 'db' => '20080228', 'text' => 'First'],
    ['human' => '5 Apr, 2009', 'db' => '20090405', 'text' => 'Second'],
    ['human' => '19 Mar, 2009', 'db' => '20090319', 'text' => 'Third'],
];

// Create an array of indices based on the numeric 'db' key
$indices = array_map('array_search', array_column($data, 'db'));

// Sort the indices based on the integer value of the 'db' column
usort($indices, function ($a, $b) use ($data) {
    return (int)$data[$a]['db'] - (int)$data[$b]['db'];
});

// Reorder the original array using the sorted indices
$sortedData = array_values(array_map(function ($index) use ($data) {
    return $data[$index];
}, $indices));

This approach performs a single logical sort operation on the internal data rather than the keys themselves. By mapping the numeric date string to an index, you ensure that the original associative structure remains intact while achieving correct chronological ordering. This is significantly more efficient than iterating three times or manipulating keys directly.

If you must work strictly with the human-readable format and no raw integer exists, you should parse the string into a DateTime object for each entry. While this requires iteration, it ensures accuracy regardless of language-specific date formatting quirks. Using DateTime::createFromFormat() allows you to extract the timestamp, which can then be used as the primary sort key:

$items = [
    ['date' => '28th February, 2009', 'content' => 'bla'],
    ['date' => '19th March, 2009', 'content' => 'bla'],
];

usort($items, function ($a, $b) {
    $fmt = 'dF Y'; // Matches "28 February 2009"
    return strtotime(str_replace('th', '', str_replace('st', '', str_replace('nd', '', str_replace('rd', '', $a['date'])))) . ',') 
         - strtotime(str_replace('th', '', str_replace('st', '', str_replace('nd', '', str_replace('rd', '', $b['date'])))) . ',');
});

Note: The parsing logic above is illustrative; in production, a regex or DateTime factory method with a custom format string is preferred to avoid fragile string manipulation.

Conclusion

The key to sorting dynamic date keys lies in separating the display value from the sort value. Never attempt to sort dates alphabetically if they contain month names or ordinal suffixes ("th", "st"). Always normalize your data into a sortable integer (Unix timestamp or Ymd format) before applying a sort function. This separation of concerns ensures that your sorting logic remains performant and independent of locale-specific date formatting rules.

Our network