Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of software versions in descending order

How can I sort this array of version values?

$available_databases = array(
    "4.0.1",
    "trunk",
    "branch",
    "4.1.0",
    "4.0.3"
);

so that the result is

4.1.0
4.0.3
4.0.1
branch
trunk
like image 324
Radek Avatar asked Feb 19 '23 08:02

Radek


1 Answers

You should use the usort function.

$isVersion = function($a) { return is_numeric( str_replace('.', '', $a) ); };
$sortFunction = function($a, $b) use($isVersion) { 
    if( $isVersion($a) && $isVersion($b) ) { 
        return version_compare($b, $a); // reversed for your proper ordering
    } elseif( $isVersion($a) ) { 
        return -1;
    } elseif( $isVersion($b) ) { 
        return 1;
    } else { 
        return strcasecmp($a, $b);
    }
};

usort($yourArray, $sortFunction);

The usort function lets you use your own custom comparison callback. I wrote one here for you with the logic you desired: if both comparable items are versions, it uses version_compare to compare them with the parameters reversed since you want descending order. If the second comparable item is a string and the first is a version, the version is said to be "lower" than the string, and vice-versa. If both items are strings, it uses the strcasecmp comparison function to determine the proper ordering.

Example in use: codepad

like image 109
Lusitanian Avatar answered Feb 21 '23 20:02

Lusitanian