title: how to find closest value in sorted array?
body: <p>I have sorted array with numbers as keys, I need a reasonably fast alg to pick a key number which is holding value closest or identical (if exists) to given variable. If given value is higher than max or lower than min values, then keys holding max and min are given respectively.</p>
  <hr />
  <p>so I made an attempt and here is a function that translates values in one array according to another, it can be used for example a temperature, -10 to cold or +30 to hot, but for big arrays it is not so fast, any clue how to make it faster ?</p>
  <pre><code>function transnum($nums,$transarr,$searchkey='x',$returnkey='y') {
  $was_arr = is_array($nums); $nums = (array)$nums;
  foreach ($nums as &amp;$num) {
      if ($num===null or $num==='') continue;
      reset($transarr[$searchkey]);
      $ckey= key($transarr[$searchkey]);
      $closest = abs($num-current($transarr[$searchkey]));
      while($next = next($transarr[$searchkey])) {
          $checkclosest=abs($num-$next);
          if($closest&gt;$checkclosest) {
              $closest = $checkclosest;
              $ckey = key($transarr[$searchkey]);
          }
          else break;
      }
      $num = $transarr[$returnkey][$ckey];
  }
  if(!$was_arr) $nums = $nums[0];
  return $nums;
  </code></pre>
  <p>}</p>