30

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)
8
  • 2
    Probably "natural order", have you tried php.net/strnatcmp ? Commented Dec 28, 2012 at 9:59
  • 4
    What's wrong with php's builtin version_compare? Commented Dec 28, 2012 at 10:00
  • 8
    Test your code before you ask. I might just work (as in your case). -1 for that. Commented Dec 28, 2012 at 10:02
  • 1
    @hakre, sorry that I didn't realize there is actually a version_compare function in PHP ... and strnatcmp also works. Commented Dec 28, 2012 at 10:13
  • 1
    @hakre, my fault. I googled all around strcmp, but... It's my fault. Commented Dec 28, 2012 at 10:19

4 Answers 4

57

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Can confirm. Just works. ALL PHP versions. 3v4l.org/U0mvm#v430 Same for the natural order compare.
10

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.

Comments

1

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

Comments

0

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

1 Comment

function new_new_version_compare($a, $b){ return explode(".", $a) <=> explode(".", $b); } ...but there's absolutely no reason to engineer a replacement for a perfectly suitable native function like version_compare().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.