Skip to content

Instantly share code, notes, and snippets.

@blood72
Last active July 8, 2021 08:36
Show Gist options
  • Save blood72/5196c44762d8e48de5a8baeb7cd737e1 to your computer and use it in GitHub Desktop.
Save blood72/5196c44762d8e48de5a8baeb7cd737e1 to your computer and use it in GitHub Desktop.
Get the closest version to a given value & Sort to version
<?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