Am I wrong or version_compare doesn't support comparing string/numbers having different "dot" length ?
Is there a quick way to compare the following without reinvent the wheel ?
version_compare(1.0, 1.0.0.0) => equal
version_compare(1.0, 1.0.0.1) => right is higher
version_compare(1.1, 1.0.0.1) => left is higher
I would do it like this;
function versionCompare($a, $b) {
$a = str_replace('.', '', $a);
$b = str_replace('.', '', $b);
$len = max(array(strlen($a), strlen($b)));
$a = (int) str_pad($a, $len, '0', STR_PAD_RIGHT);
$b = (int) str_pad($b, $len, '0', STR_PAD_RIGHT);
if ($a === $b) {
// Versions are equal
} elseif ($a > $b) {
// First version is higher
} else {
// Last version is higher
}
}
Am I wrong or version_compare doesn't support comparing string/numbers having different "dot" length ?
Is there a quick way to compare the following without reinvent the wheel ?
version_compare(1.0, 1.0.0.0) => equal
version_compare(1.0, 1.0.0.1) => right is higher
version_compare(1.1, 1.0.0.1) => left is higher
I would do it like this;
function versionCompare($a, $b) {
$a = str_replace('.', '', $a);
$b = str_replace('.', '', $b);
$len = max(array(strlen($a), strlen($b)));
$a = (int) str_pad($a, $len, '0', STR_PAD_RIGHT);
$b = (int) str_pad($b, $len, '0', STR_PAD_RIGHT);
if ($a === $b) {
// Versions are equal
} elseif ($a > $b) {
// First version is higher
} else {
// Last version is higher
}
}
0 commentaires:
Enregistrer un commentaire