Mojilo Mojilo - 29 days ago 8
PHP Question

How to sort date array in php?

I am new to php, I have php date array

[0] => 11-01-2012
[1] => 01-01-2014
[2] => 01-01-2015
[3] => 09-02-2013
[4] => 01-01-2013


I want to sort it like :

[0] => 11-01-2012
[1] => 01-01-2013
[2] => 09-02-2013
[3] => 01-01-2014
[4] => 01-01-2015


I use
asort
but not working.

Answer

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