Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Created February 17, 2012 21:41
Show Gist options
  • Save jehoshua02/1855624 to your computer and use it in GitHub Desktop.
Save jehoshua02/1855624 to your computer and use it in GitHub Desktop.
Comparing software versions ...
<?php
function compare_version($version_a, $version_b, $limit = 2)
{
$a_segments = explode('.', $version_a);
$b_segments = explode('.', $version_b);
$sentinel = min(sizeof($a_segments), $limit);
for ($i = 0; $i < $sentinel; $i++)
{
$a = (isset($a_segments[$i])) ? $a_segments[$i] : 0;
$b = (isset($b_segments[$i])) ? $b_segments[$i] : 0;
if ($a != $b)
{
if ($a > $b) return 1;
else if ($a < $b) return -1;
}
}
return 0;
}
<?php
$comparisons = array(
array('2.10.11', '2.11.5', -1),
array('2.13.15', '2.2.3', 1),
array('1.1.1', '1.1.1', 0)
);
foreach ($comparisons as $k => $comparison)
{
list($a, $b, $expected) = $comparison;
$actual = ci_version_compare($a, $b);
$test = "{$actual} == {$expected}; // {$a} and {$b} ({$expected})";
assert($test);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment