PHP: version_compare() returns -1 when comparing 5.2 and 5.2.0?

5.2 and 5.2.0 are both PHP-standardized version number strings. AFAIU 5.2 represents 5.2.0, 5.2.1, etc. And result is logical, 5.2 could not be equal to 5.2.1 or 5.2.0 and either it could not be greater than 5.2.0 for example.
So only expected behavior is 5.2 < 5.2.0, 5.2 < 5.2.1, ...

Btw even the documentation states:

This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also ...


Here's a tweaked compare function which behaves as expected by trimming zero version suffix components, i.e. 5.2.0 -> 5.2.

var_dump(my_version_compare('5.1', '5.1.0'));           //  0 - equal
var_dump(my_version_compare('5.1', '5.1.0.0'));         //  0 - equal
var_dump(my_version_compare('5.1.0', '5.1.0.0-alpha')); //  1 - 5.1.0.0-alpha is lower
var_dump(my_version_compare('5.1.0-beta', '5.1.0.0'));  // -1 - 5.1.0-beta is lower

function my_version_compare($ver1, $ver2, $operator = null)
{
    $p = '#(\.0+)+($|-)#';
    $ver1 = preg_replace($p, '', $ver1);
    $ver2 = preg_replace($p, '', $ver2);
    return isset($operator) ? 
        version_compare($ver1, $ver2, $operator) : 
        version_compare($ver1, $ver2);
}

The documentation says it compares 'two "PHP-standardized" version number strings'.

You're comparing one PHP-standardized version number string with one non-PHP-standardized version number string.

Tags:

Php