Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort versioning info

What's the right way, to handle versioning indicators like 2.4 or 2.4.0.9 etc. to get the ability of sorting versions.

PHP says, that 1.3.4 is not a valid integer, but also a non-valid number.

array('2.4','2.3.4','2.4.0.9')
like image 376
mate64 Avatar asked Dec 31 '11 22:12

mate64


People also ask

How do you sort semantic versioning?

If you find yourself having to sort using semantic version strings, (sorting a list of releases chronologically, say), we first need to split the string into its values and then compare each value. In this case we would sort by major release first, then minor, then finally by patch number.

What is semantic versioning format?

Semantic versioning is a formal convention for determining the version number of new software releases. The standard helps software users to understand the severity of changes in each new distribution. A project that uses semantic versioning will advertise a Major, Minor and Patch number for each release.

How do I compare versions in Java?

Compare two version numbers version1 and version2. If version1 > version2 return 1; if version1 < version2 return -1; otherwise return . You may assume that the version strings are non-empty and contain only digits and the . character.


3 Answers

PHP has a version_compare function. Use usort to sort it. Like following. :)

$a = array('2.4','2.3.4','2.4.0.9');
usort($a, 'version_compare');
like image 56
Shiplu Mokaddim Avatar answered Oct 01 '22 10:10

Shiplu Mokaddim


Or, just use natsort:

$array = array('2.4','2.16.6','2.3.4','2.4.0.9');
natsort($array);
print_r($array);

#Array ( [2] => 2.3.4 [0] => 2.4 [3] => 2.4.0.9 [1] => 2.16.6 )
like image 21
benesch Avatar answered Oct 02 '22 10:10

benesch


Storing it as a string allows you to make use of the version_compare() function:

$versions = array('2.4','2.3.4','2.4.0.9');
usort($versions, 'version_compare');
like image 29
Tim Cooper Avatar answered Sep 30 '22 10:09

Tim Cooper