Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a matching or closest value in an array

How can I search and find, for a given target value, the closest value in an array?

Let's say I have this exemplary array:

array(0, 5, 10, 11, 12, 20) 

For example, when I search with the target value 0, the function shall return 0; when I search with 3, it shall return 5; when I search with 14, it shall return 12.

like image 463
FMaz008 Avatar asked Mar 28 '11 20:03

FMaz008


1 Answers

Pass in the number you're searching for as the first parameter and the array of numbers to the second:

function getClosest($search, $arr) {    $closest = null;    foreach ($arr as $item) {       if ($closest === null || abs($search - $closest) > abs($item - $search)) {          $closest = $item;       }    }    return $closest; } 
like image 76
Tim Cooper Avatar answered Sep 21 '22 10:09

Tim Cooper