Skip to content

Instantly share code, notes, and snippets.

@cetver
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cetver/8859335 to your computer and use it in GitHub Desktop.
Save cetver/8859335 to your computer and use it in GitHub Desktop.
<?php
function getClosest($needle, $haystack, $highestOnEqual = true) {
if ($highestOnEqual === true) {
rsort($haystack, SORT_NUMERIC);
} else {
asort($haystack, SORT_NUMERIC);
}
$value = current($haystack);
foreach ($haystack as $val) {
if (abs($needle - $value) > abs($val - $needle)) {
$value = $val;
}
}
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment