Skip to content

Instantly share code, notes, and snippets.

@iainmullan
Created September 17, 2014 15:36
Show Gist options
  • Save iainmullan/aaba2eceb6ed87063bd8 to your computer and use it in GitHub Desktop.
Save iainmullan/aaba2eceb6ed87063bd8 to your computer and use it in GitHub Desktop.
Compare version numbers of the format X.Y.Z (major.minor.patch)
<?php
/**
* Compare version numbers of the format X.Y.Z where X,Y,Z are non-negative integers
* Values with less than three parts will be padded out with zeros, eg. "1.1" becomes "1.1.0", "1" becomes "1.0.0"
*
* @return 1 if $a is greater (a later version) than $b, 0 if $a is equal to $b, -1 if $a is less (an earlier version) than $b
*
*/
function version_cmp($a, $b) {
$nums1 = explode('.',$a);
$nums2 = explode('.',$b);
$nums1 = array_pad($nums1, 3, '0');
$nums2 = array_pad($nums2, 3, '0');
if($nums1[0] < $nums2[0]) {
// $a is a major version BEHIND
return -1;
} else if ($nums1[0] > $nums2[0]) {
// $a is a major version AHEAD
return 1;
} else {
// major versions are equal
if ($nums1[1] < $nums2[1]) {
// $ a is a minor version BEHIND
return -1;
} else if ($nums1[1] > $nums2[1]) {
// $ a is a minor version AHEAD
return 1;
} else {
if ($nums1[2] < $nums2[2]) {
// $ a is a patch version BEHIND
return -1;
} else if ($nums1[2] > $nums2[2]) {
// $ a is a patch version AHEAD
return 1;
} else {
// version numbers match EXACTLY
return 0;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment