note 125466 deleted from function.version-compare by cmb
| From: | cmb@php.net | Date: | Mon, 26 Oct 2020 16:12:23 +0000 |
| Subject: | note 125466 deleted from function.version-compare by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215657@lists.php.net to get a copy of this message | ||
Note Submitter: jordyelfferich15 at gmail dot com
----
I wrote a more reliable and straightforward function (as compared to other solutions posted here) to
compare versions. But does not support the operator argument like in the original.
<?php
function compareVersions($left, $right)
{
$leftParts = explode('.', $left);
$rightParts = explode('.', $right);
$leftCount = count($leftParts);
$rightCount = count($rightParts);
for ($i = 0; $i < max($leftCount, $rightCount); $i++) {
$leftPart = (int)($leftParts[$i] ?? 0);
$rightPart = (int)($rightParts[$i] ?? 0);
if ($leftPart !== $rightPart) {
return $leftPart > $rightPart ? 1 : -1;
}
}
return 0;
}
?>