Sling Academy
Home/PHP/PHP: How to sort an array of dates in DESC/ASC order

PHP: How to sort an array of dates in DESC/ASC order

Last updated: January 09, 2024

Introduction

Sorting arrays is a fundamental task in programming, and when it comes to sorting dates, PHP offers several functions that make the process intuitive. Whether ascending or descending, understanding how to sort dates properly is essential for time-based data manipulation.

Using usort with strtotime

To begin sorting an array of dates, you can use the usort function in combination with the strtotime function. This approach allows for custom sorting logic and can be easily adapted for both ascending and descending orders.


$dates = array(
    '2023-03-25',
    '2023-02-15',
    '2023-04-01'
);

usort($dates, function($a, $b) {
    return strtotime($a) - strtotime($b);
});

print_r($dates); // Output will be in ascending order

To sort in descending order, simply invert the subtraction in the comparison function.


usort($dates, function($a, $b) {
    return strtotime($b) - strtotime($a);
});

print_r($dates); // Output will be in descending order

Sorting with DateTime Class

Another approach involves the DateTime class, which provides a more object-oriented way to work with dates and sorting.


$dates = array(
    new DateTime('2023-03-25'),
    new DateTime('2023-02-15'),
    new DateTime('2023-04-01')
);

usort($dates, function($a, $b) {
    return $a <=> $b;
});

foreach ($dates as $date) {
    echo $date->format('Y-m-d') . '\\n';
} // Outputs ascending order

Use the spaceship operator <=> to sort objects. To sort in reverse, simply flip $a and $b.


usort($dates, function($a, $b) {
    return $b <=> $a;
});

foreach ($dates as $date) {
    echo $date->format('Y-m-d') . '\\n';
} // Outputs descending order

Array Multisort with Extracted Timestamps

The array_multisort function can simultaneously sort multiple arrays or multi-dimensional arrays. By extracting timestamps from the dates, you can use array_multisort to order them.


$dates = array(
    '2023-03-25',
    '2023-02-15',
    '2023-04-01'
);
$timestamps = array_map('strtotime', $dates);

array_multisort($timestamps, SORT_ASC, $dates);

print_r($dates); // Output will be in ascending order

// For descending order, change SORT_ASC to SORT_DESC
array_multisort($timestamps, SORT_DESC, $dates);

print_r($dates); // Output will be in descending order

Integration with Database Queries

Sorting can also be done directly within database queries, optimizing performance. Use SQL’s ORDER BY clause to sort dates before they are even fetched into the array.


// Using PDO for a MySQL query
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'user', 'password');
$stmt = $pdo->query('SELECT * FROM your_table ORDER BY your_date_column ASC');

$dates = $stmt->fetchAll(PDO::FETCH_ASSOC);

// The $dates array is now sorted in ascending order

This method is particularly effective for large datasets where PHP-level sorting may become inefficient.

Performance Considerations

When dealing with large arrays, it’s important to consider the performance of your sorting algorithm. Functions like usort with strtotime can be resource-intensive, so for larger datasets, pre-computing timestamps or sorting within the database may provide better performance.

Conclusion

In conclusion, PHP lends you a versatile set of functions to sort an array of dates in either ascending or descending order. Experiment with different methods to find the perfect balance between readability and performance for your particular use case. With a little practice, sorting dates will become second nature in your PHP development journey.

Next Article: PHP: Calculate people’s age from date of birth

Previous Article: Working with Daylight Saving Time in PHP

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array