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\") =&
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.
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;
}
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.
what you could do is parse each string, stop at the dot and add each number into a separate int.
so that your string 2.5.1 would become 3 integers:
$ver1 . "." . $ver2 . "." . $ver3
and your string 2.5.11 would become:
$ver1_2 . "." . $ver2_2 . "." . $ver3_2
then a bunch of if's to compare $ver1 with $ver1_2 and so on.
I have developed this function. I hope it helps. It can go to any length.
function updateAppVersion($appVersion1, $appVersion2)
{
$releaseVersion = explode(".",$appVersion1);
$deviceVersion = explode(".",$appVersion2);
$len = count($deviceVersion);
if(count($releaseVersion)>count($deviceVersion)){
$len = count($releaseVersion);
}
for($i = 0;$i<$len;$i++){
echo "[i=".$i."][r=".$releaseVersion[$i]."][d=".$deviceVersion[$i]."]";
if(!isset($releaseVersion[$i])){
return false;
}
else if(!isset($deviceVersion[$i])){
return true;
}
else if($releaseVersion[$i]>$deviceVersion[$i]){
return true;
}
else if($releaseVersion[$i]<$deviceVersion[$i]){
return false;
}
}
return false;
}