Compare two version strings in PHP

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.


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.

Tags:

Php