-1 (smaller) versi...">

Comparing two version lines in PHP

How to compare two lines 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) 
+6
source share
5 answers

From the PHP interactive prompt using the version_compare function built into PHP since version 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 

PHP seems to work as you expect. If you encounter other behaviors, you should probably indicate this.

+23
source

If your comparison option does not work, the code below will give 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; } 
0
source

Alternatively, you can use the PHP built-in function as shown below by passing the optional argument version_compare()

 if(version_compare('2.5.2', '2.5.1', '>')) { print "First arg is greater than second arg"; } 

See version_compare for further queries.

0
source

The marked answer is not suitable for the case:

print_r (version_compare ("2.51.1", "2.5.1"));

Here's a more robust solution:

 function updateAppVersion($appVersion1, $appVersion2) { $releaseVersion = explode(".",$appVersion1); $deviceVersion = explode(".",$appVersion2); if($releaseVersion[0] > $deviceVersion[0]) return false; if((floatval($releaseVersion[0].'.'.$releaseVersion[1])) > (floatval($deviceVersion[0].'.'.$deviceVersion[1]))) return false; //in some cases, versions are numbered only up to 2 decimal places if(isset($releaseVersion[2]) && isset($deviceVersion[2])) if($releaseVersion[2] >= $deviceVersion[2]) return false; return true; } 
0
source

what you could do is analyze each line, stop at a point and add each number to a separate int.

so that your line 2.5.1 becomes 3 integers:

 $ver1 . "." . $ver2 . "." . $ver3 

and your line 2.5.11 becomes the following:

 $ver1_2 . "." . $ver2_2 . "." . $ver3_2 

then heap, if you compare $ ver1 with $ ver1_2, etc.

-2
source

All Articles