
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Sort an array of dates in PHP
To sort an array of dates in PHP, the code is as follows−
Example
<?php function compareDates($date1, $date2){ return strtotime($date1) - strtotime($date2); } $dateArr = array("2019-11-11", "2019-10-10","2019-08-10", "2019-09-08"); usort($dateArr, "compareDates"); print_r($dateArr); ?>
Output
This will produce the following output−
Array ( [0] => 2019-08-10 [1] => 2019-09-08 [2] => 2019-10-10 [3] => 2019-11-11 )
Example
Let us now see another example −
<?php function compareDates($date1, $date2){ if (strtotime($date1) < strtotime($date2)) return 1; else if (strtotime($date1) > strtotime($date2)) return -1; else return 0; } $dateArr = array("2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11", "2019-01-01"); usort($dateArr, "compareDates"); print_r($dateArr); ?>
Output
This will produce the following output−
Array ( [0] => 2019-11-11 [1] => 2019-11-11 [2] => 2019-10-10 [3] => 2019-09-08 [4] => 2019-05-11 [5] => 2019-01-01 )
- Related Articles
- PHP program to sort dates given in the form of an array
- Return all dates between two dates in an array in PHP
- How to sort an array of dates in C/C++?
- Comparison of dates in PHP
- Sort php multidimensional array by sub-value in PHP
- Sort an Array of string using Selection sort in C++
- Sort multidimensional array by multiple keys in PHP
- Sort an Array in C++
- Comparing two dates in PHP
- Sort by index of an array in JavaScript
- How to store all dates in an array present in between given two dates in JavaScript?
- Sort an array according to another array in JavaScript
- Odd even sort in an array - JavaScript
- How to sort an array in C#?
- How to use std::sort to sort an array in C++

Advertisements