PHP:version_compare()在比较5.2和5.2.0时返回-1?

PHP:version_compare()在比较5.2和5.2.0时返回-1?

问题描述:

version_compare('5.2', '5.2.0'); // returns -1, as if the second parameter is greater!

Isn't 5.2 and 5.2.0 suppose to be equal? (isn't 5.2 and 5.2.0.0 are also equal)?

  version_compare('5.2','5.2.0');  //返回-1,好像第二个参数更大!
  code>  pre> 
 
 

5.2和5.2.0是否相等? (不是5.2和5.2.0.0也相等)? p> div>

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.

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);
}