Sorting Date Arrays in PHP
PHP provides several ways to sort arrays, including date arrays. This article will demonstrate how to sort a PHP date array according to date values.
Problem:
Consider the following PHP date array:
<code class="php">[0] => 11-01-2012 [1] => 01-01-2014 [2] => 01-01-2015 [3] => 09-02-2013 [4] => 01-01-2013</code>
The goal is to sort the array in ascending order of dates, resulting in the following sorted array:
<code class="php">[0] => 11-01-2012 [1] => 01-01-2013 [2] => 09-02-2013 [3] => 01-01-2014 [4] => 01-01-2015</code>
Solution:
If the dates in the array are stored in the format "Y-m-d" or "Y-m-d H:i:s," you can sort the array directly using sort():
<code class="php">$arr = ["2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11"]; sort($arr);</code>
However, if the date format is localized or not in a sortable format, you need to use a custom sorting function such as usort(). This function compares two elements of the array, converts them into a sortable format, and returns a value that indicates the sorting order:
<code class="php">$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); });</code>
The above is the detailed content of How to Sort Date Arrays Ascendingly in PHP?. For more information, please follow other related articles on the PHP Chinese website!