Created
December 6, 2020 16:09
-
-
Save fatihgune/1db531eebd39bb0392ea6f3745bda9e0 to your computer and use it in GitHub Desktop.
Get the closest number in array (PHP)
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
<? | |
/** | |
* @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