How to Sort Date Arrays Ascendingly in PHP?

Susan Sarandon
Release: 2024-10-21 20:30:03
Original
416 people have browsed it

How to Sort Date Arrays Ascendingly in PHP?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!