PHP Sort a multidimensional array by element containing Y-m-d H:i:s date

PHP Sort a multidimensional array by element containing Y-m-d H:i:s date

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

Stefan Bogdanescu

Founder & Senior Architect

Sorting Multidimensional Arrays by DateTime in PHP

Sorting a multidimensional array in PHP requires bridging the gap between structural data and scalar comparison logic. When your dataset contains associative sub-arrays, standard sorting functions cannot simply compare two integers or strings; they need to know which specific key within each sub-array holds the value you wish to order by. In the case of timestamps formatted as Y-m-d H:i:s, PHP's native capabilities handle this elegantly without needing external date parsing libraries.

The most robust and modern approach for this task is leveraging the usort() function combined with a custom callback. While sort(), rsort(), asort(), and arsort() exist, they are limited to sorting by the index of the array or the value directly. To sort by a nested key like datetime, you must provide a comparison function that returns an integer indicating the order.

Consider the array structure provided:

$items = [
    [
        'id' => 2,
        'type' => 'comment',
        'text' => 'hey',
        'datetime' => '2010-05-15 11:29:45'
    ],
    [
        'id' => 3,
        'type' => 'status',
        'text' => 'oi',
        'datetime' => '2010-05-26 15:59:53'
    ],
    [
        'id' => 4,
        'type' => 'status',
        'text' => 'yeww',
        'datetime' => '2010-05-26 16:04:24'
    ]
];

To sort $items chronologically, you implement a callback function for usort(). The logic inside this function is critical. You extract the timestamp strings from both the left-hand argument ($a) and the right-hand argument ($b). Because PHP's string comparison operators work lexicographically (alphabetically), comparing two ISO 8601 formatted datetime strings directly yields the correct chronological result.

usort($items, function ($a, $b) {
    // Extract the datetime strings
    $timeA = $a['datetime'];
    $timeB = $b['datetime'];

    // Perform string comparison
    if ($timeA == $timeB) {
        return 0;
    }
    return ($timeA < $timeB) ? -1 : 1;
});

This implementation avoids the overhead of converting strings to Unix timestamps using strtotime() or DateTime objects unless necessary. String comparison is O(n) relative to string length, which is negligible for standard datetime formats, making this approach performant and memory-efficient. It relies on the guarantee that the input format is consistent. If your data source occasionally returns a different format (e.g., d/m/Y), lexicographical sorting will fail catastrophically.

An alternative method available in PHP 5.4+ is using array_column() to extract just the datetime column, sort it, and then re-index or map back if needed. However, this is often overkill and less readable than a direct usort callback when dealing with complex objects containing multiple metadata fields alongside the timestamp.

There is also the built-in uasort(), which preserves the original keys of the array. If your application relies on these keys for database lookups or session management, usort() will re-index them to 0, 1, 2, potentially breaking downstream logic. In such cases, you must explicitly preserve the keys:

usort($items, function ($a, $b) {
    return strtotime($a['datetime']) - strtotime($b['datetime']);
});
// Note: This re-indexes keys. To keep them, use uasort instead.

In modern PHP applications, particularly those built on the Laravel framework, sorting is often handled at the query level using Eloquent or DB::table. If you are fetching this data directly from a database, relying on SQL's ORDER BY clause is generally more efficient than loading the full dataset into PHP memory and sorting it client-side. However, when working with pre-existing arrays in memory—perhaps fetched via JSON responses or complex joins where sorting in SQL was insufficient—the usort() pattern remains a standard, reliable utility in the PHP developer's toolkit.

Our network