Last active
July 8, 2021 08:36
-
-
Save blood72/5196c44762d8e48de5a8baeb7cd737e1 to your computer and use it in GitHub Desktop.
Get the closest version to a given value & Sort to version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (! function_exists('version_sort')) { | |
/** | |
* Sort array with version_compare. | |
* @link https://stackoverflow.com/a/48974986/5067386 | |
* @param string[] $versions | |
* @return void | |
*/ | |
function version_sort(array $versions) { | |
usort($versions, function ($version1, $version2) { | |
return -1 * version_compare($version1, $version2); | |
}); | |
} | |
} | |
if (! function_exists('version_search')) { | |
/** | |
* Get the closest version to a given value. | |
* | |
* @param string $search | |
* @param string[] $versions | |
* @return string|null | |
*/ | |
function version_search(string $search, array $versions): ?string | |
{ | |
foreach ($versions as $version) { | |
if (version_compare($search, $version, '>=')) { | |
return $version; | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment