Reputation: 51921
How to compare two strings in version format? such that:
version_compare("2.5.1", "2.5.2") => -1 (smaller)
version_compare("2.5.2", "2.5.2") => 0 (equal)
version_compare("2.5.5", "2.5.2") => 1 (bigger)
version_compare("2.5.11", "2.5.2") => 1 (bigger, eleven is bigger than two)
Upvotes: 29
Views: 25222
Reputation: 2289
Check out https://github.com/composer/semver.
comparison example:
use Composer\Semver\Comparator;
Comparator::greaterThan('1.25.0', '1.24.0'); // 1.25.0 > 1.24.0
Upvotes: 1
Reputation: 143
Also, you can use the PHP built-in function as below by passing an extra argument to the version_compare()
if(version_compare('2.5.2', '2.5.1', '>')) {
print "First arg is greater than second arg";
}
Please see version_compare for further queries.
Upvotes: 7
Reputation: 51411
From the PHP interactive prompt using the version_compare
function, built in to PHP since 4.1:
php > print_r(version_compare("2.5.1", "2.5.2")); // expect -1
-1
php > print_r(version_compare("2.5.2", "2.5.2")); // expect 0
0
php > print_r(version_compare("2.5.5", "2.5.2")); // expect 1
1
php > print_r(version_compare("2.5.11", "2.5.2")); // expect 1
1
It seems PHP already works as you expect. If you are encountering different behavior, perhaps you should specify this.
Upvotes: 56
Reputation: 2577
If your version compare doesnt work, the code below will produce your results.
function new_version_compare($s1,$s2){
$sa1 = explode(".",$s1);
$sa2 = explode(".",$s2);
if(($sa2[2]-$sa1[2])<0)
return 1;
if(($sa2[2]-$sa1[2])==0)
return 0;
if(($sa2[2]-$sa1[2])>0)
return -1;
}
Upvotes: 0