Question

Just wondering if anyone can optimize this usortMonths() function to be better? Basically I have an array of months unsorted, $bob, and I want them sorted by month, not alphabetically.

The code works fine, but its my first time with uSort and I wouldnt mind if anyone can give any suggestions of improvement?

function usortMonths($a, $b) {
$months = array('JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER');
    $key = array(0 => 0,1 => 0,2 => FALSE, 3 => FALSE);
    if(array_search(strtoupper($a),$months)!==FALSE) {
        $key[0] = array_search(strtoupper($a),$months);
        $key[2] = TRUE; }
    if(array_search(strtoupper($b),$months)!==FALSE) {
        $key[1] = array_search(strtoupper($b),$months);
        $key[3] = TRUE; }
    if($key[2] && $key[3]){
        if($key[0] < $key[1]) {return -1;}
        if($key[0] == $key[1]){return 0;}
        if($key[0] > $key[1]) {return 1;}
    }
}

$bob = array('april','august','december','february','January','july','june','march','may','november','october','september',);       
usort($bob,"usortMonths");
var_dump($bob);
Was it helpful?

Solution

How about this?

function usortMonths($a, $b) {
    $months = array('JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER');
    return array_search(strtoupper($a), $months) - array_search(strtoupper($b), $months);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top