"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort Date Arrays in PHP for Different Formats?

How to Sort Date Arrays in PHP for Different Formats?

Published on 2024-11-01
Browse:259

How to Sort Date Arrays in PHP for Different Formats?

Sorting Date Arrays in PHP

When working with PHP, you may encounter situations where you need to sort date arrays in chronological order. One common challenge is ensuring that dates follow the desired format.

For dates in "Mysql" format (Y-m-d or Y-m-d H:i:s), sorting can be straightforward:

$arr = ["2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11"];
sort($arr);

However, for localized or formatted dates, a custom sorting function is necessary. One approach is to convert the dates into sortable format using strtotime():

$arr = ['11/01/2012', '03/16/2022', '12/26/2021', '01/01/2014', '09/02/2013'];
usort($arr, function ($a, $b) {
    return strtotime($a) - strtotime($b);
});

This method converts the dates into Unix timestamps, which can be easily sorted.

It's important to note that using strtotime() assumes that all dates are in the expected format. If different formats are present in your array, consider explicitly defining the format, as explained in the reference article.

Release Statement This article is reprinted at: 1729513878 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3