Skip to content

Instantly share code, notes, and snippets.

@fatihgune
Created December 6, 2020 16:09
Show Gist options
  • Save fatihgune/1db531eebd39bb0392ea6f3745bda9e0 to your computer and use it in GitHub Desktop.
Save fatihgune/1db531eebd39bb0392ea6f3745bda9e0 to your computer and use it in GitHub Desktop.
Get the closest number in array (PHP)
<?
/**
* @param mixed $search
* @param array $arr
* @return mixed|null
*/
public function getClosestNumber($search, array $arr)
{
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment