title: Get nearest values without loop in array using PHP
body: <p>Given an array :</p>
  
  <pre><code>   $foo = Array(
           99=&gt;'Lowest Numbers',
          123=&gt;'Low Numbers',
          456=&gt;'High Numbers',
          777=&gt;'Highest Numbers',
     );
  </code></pre>
  
  <p>... and the value '144',  I would like to return the nearest low value, and nearest high value without having to loop through each element in the array as the actual array is quite large.</p>
  
  <p>The expected result from '144' would be 123=>'Low Numbers'</p>
  
  <p>I currently have the following code :</p>
  
  <pre><code>    function name($color,$fuzzy=false) {
          global $resene;
          $long = 0;
          if(is_array($color)) {
              $long = Color::hex2lng(Color::rgb2hex($color));
          } else {
              $long = Color::hex2lng($color);
          }
  
          if(isset($resene[$long])) {
              echo $resene[$long];
          } else {
              if($fuzzy) {
                  $resene[$long] = '';
                  ksort($resene);
  
                  // This is where I am having problems
                                      // The array is sorted, so it should be a simple
                                      // matter of getting the previous and next value
                                      // somehow since we know the position we want to
                                      // start at exists because it has been added.
  
                  echo 'No color name found';
              }
          }
      }
  </code></pre>
  
  <p>Basically, the concept is pretty straightforward since we are injecting the value that wasn't found into the array, we know it exists.  Sorting on key, now ensures that the two closest keys are the closest matches to the number being searched for.</p>
  
  <p>The above function is actually a search based on Hex or RGB color that is converted to base 10 ( long value ).</p>
  
  <p>The keys in the array are non-incremental, meaning it isn't 0,1,2,3, and even if i 'flipped' the array, the keys would then be strings, and again, nothing incremental to get the closest.</p>
  
  <p>I was considering a split or something, however that seems to split the array based on how many elements in -- not based on the key.</p>
  
  <p>This is essentially the last step to make this work -- without having to loop through every element.</p>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>Here is a Pastbin of the Static function I wrote which returns an Array() of Colors using the Long value of the color as the Key and the Value is the String Name of the color.</p>
  
  <p><a href="http://pastebin.com/pkAL9CTy" rel="nofollow">Color Index Array</a></p>