Posted by & filed under Programming.

Needed a quick way to sort on version numbers, and PHP has a usort function that makes it pretty easy.

You’ll need an array to sort and call the usort function with a callback.

$ray = array("1.1", "2.4", "0.7", "1.1.b");
usort($ray, 'versionSort');

Now the callback. We’re going to use version_compare.

function versionSort($a, $b) {
return -1 * version_compare($a, $b);

Only minor quirk is the * -1 to flip version compare. I wanted the newest version at the 0 spot. You could also just swap $a and $b to do the same thing. This just made more sense to me for when I come back and look at it down the road.

2 Responses to “Sorting on version numbers with PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *