How to sort date array in php?
Because array items is string, you need to convert them to date and then comparing to sort. The usort()
sort array using custom function that is a good sort function for this case.
$arr = array('11-01-2012', '01-01-2014', '01-01-2015', '09-02-2013', '01-01-2013');
function date_sort($a, $b) {
return strtotime($a) - strtotime($b);
}
usort($arr, "date_sort");
print_r($arr);
Check result in demo
out of the box use time function to generate ts and sort
<?php
$out = array();
// $your_array is the example obove
foreach($your_array as $time) {
$out[strtotime($time)] = $time;
}
// now $out has ts-keys and you can handle it
...
?>
ksort
Try this,
<?php
$array = [ '11-01-2012', '01-01-2014', '01-01-2015', '09-02-2013', '01-01-2013' ];
function sortFunction( $a, $b ) {
return strtotime($a) - strtotime($b);
}
usort($array, "sortFunction");
var_dump( $array );
?>
Will sort the dates into the order you want.
Try below code:
<?php
$array = array('11-01-2012','01-01-2011','09-02-2013','01-01-2014','01-01-2015');
function cmp($a, $b)
{
$a = date('Y-m-d', strtotime($a));
$b = date('Y-m-d', strtotime($b));
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($array, "cmp");
foreach ($array as $key => $value) {
echo "[$key]=> $value <br>";
}
?>