Created
October 13, 2020 09:44
-
-
Save utkarsh27a/f9a5123f3dd725445a8c9e87f0be4917 to your computer and use it in GitHub Desktop.
a simple 2 version compare function in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function versionCompare($v1, $v2) { | |
# This will split both the versions by '.' | |
$v1parts = explode(".", $v1); | |
$v2parts = explode(".", $v2); | |
# converts to integer from string | |
$v1parts = array_map(intval, $v1parts); | |
$v2parts = array_map(intval, $v2parts); | |
# compares which list is bigger and fills | |
# smaller list with zero (for unequal delimeters) | |
if (count($v1parts) > count($v2parts)) | |
for ($i=0; $i < count($v1parts); $i++) | |
$v2parts.append(0); | |
elseif (count($v1parts) < count($v2parts)) | |
for ($i=0; $i < count($v2parts); $i++) | |
$v1parts.append(0); | |
# returns 1 if version 1 is bigger and -1 if | |
# version 2 is bigger and 0 if equal | |
for ($i=0; $i < count($v1parts); $i++) { | |
if ($v1parts[$i] > $v2parts[$i]) | |
return 1; | |
elseif ($v2parts[$i] > $v1parts[$i]) | |
return -1; | |
} | |
return 0; | |
} | |
# Driver program to check above comparison function | |
$version1 = "1.11.3"; | |
$version2 = "1.50.7"; | |
$ans = versionCompare($version1, $version2); | |
if ($ans < 0) | |
print ($version1 . " is smaller"); | |
elseif ($ans > 0) | |
print( $version2 . " is smaller"); | |
else | |
print("Both versions are equal"); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment