Skip to content

Instantly share code, notes, and snippets.

@kphrx
Last active January 19, 2018 08:58
Show Gist options
  • Save kphrx/046a6950269877d12bd2d2cbb8ef8de9 to your computer and use it in GitHub Desktop.
Save kphrx/046a6950269877d12bd2d2cbb8ef8de9 to your computer and use it in GitHub Desktop.
version list sort
<?php
require('VersionSort.php');
$versionArray = ['2.0.0', '1.1.0', '1.0.0', '1.1.0-dev', '2.0.0-dev'];
VersionSort::ascendingSort($versionArray);
print_r($versionArray);
/*
Array
(
[0] => 1.0.0
[1] => 1.1.0-dev
[2] => 1.1.0
[3] => 2.0.0-dev
[4] => 2.0.0
)
*/
VersionSort::descendingSort($versionArray);
print_r($versionArray);
/*
Array
(
[0] => 2.0.0
[1] => 2.0.0-dev
[2] => 1.1.0
[3] => 1.1.0-dev
[4] => 1.0.0
)
*/
<?php
class VersionSort {
public static function ascendingSort(array &$versionArray) {
return usort($versionArray, 'self::ascendingCompare');
}
public static function descendingSort(array &$versionArray) {
return usort($versionArray, 'self::descendingCompare');
}
private static function ascendingCompare($a, $b) {
if (version_compare($a, $b, '=='))
return 0;
return version_compare($a, $b, '<') ? -1 : 1;
}
private static function descendingCompare($a, $b) {
if (version_compare($a, $b, '=='))
return 0;
return version_compare($a, $b, '>') ? -1 : 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment