phparrayssortingchronological

Sort an array of 3-letter month names chronologically


Is there a way I can sort the following array into the correct chronological order?

Array
(
    [0] => apr
    [1] => aug
    [2] => dec
    [3] => feb
    [4] => jan
    [5] => jul
    [6] => jun
    [7] => mar
    [8] => may
    [9] => nov
    [10] => oct
    [11] => sep
)

NOTE The array comes to me like this, and sometimes it will not have all the months.


Solution

  • function sort_months($item_1, $item_2)
    {
        $item_1 = strtotime('1 ' . $item_1 . ' 2000');
        $item_2 = strtotime('1 ' . $item_2 . ' 2000');
        if($item_1 == $item_2)
        {
            return 0;
        }
        return $item_1 > $item_2 ? 1 : -1;
    }
    
    $arr = array
    (
        'apr',
        'aug',
        'dec',
        'feb',
        'jan',
        'jul',
        'jun',
        'mar',
        'may',
        'nov',
        'oct',
        'sep'
    );
    
    usort($arr, 'sort_months');