function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
http://stackoverflow.com/questions/5464919/php-nearest-value-from-an-array
I've the following array:
array(0, 5, 10, 11, 12, 20)
How can I find find the "nearest" value of a needle?
Examples:
function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
등록된 댓글이 없습니다.