'Compare two version strings in PHP

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)
php


Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kiran Tej
Solution 3