Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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)?

like image 920
evilReiko Avatar asked Jun 12 '12 13:06

evilReiko


3 Answers

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.

like image 138
ceejayoz Avatar answered Oct 17 '22 19:10

ceejayoz


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);
}
like image 36
Paul Avatar answered Oct 17 '22 20:10

Paul


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 ...

like image 4
Dattaya Avatar answered Oct 17 '22 20:10

Dattaya