title: binary in_array search
body: <p>I use a lot of <code>in_array</code> functions and it seems to bog down my loading times. I found the following code in the <a href="http://php.net/manual/en/function.in-array.php" rel="nofollow"><code>in_array</code> php documentation</a>. The writer states "this function is five times faster than in_array(). It uses a binary search and should be able to be used as a direct replacement." </p>
  
  <pre><code>function fast_in_array($elem, $array) 
  {
     $top = sizeof($array) -1;
     $bot = 0;
     while($top &gt;= $bot) 
     {
        $p = floor(($top + $bot) / 2);
        if ($array[$p] &lt; $elem) $bot = $p + 1;
        elseif ($array[$p] &gt; $elem) $top = $p - 1;
        else return TRUE;
     }
     return FALSE;
  }
  </code></pre>
  
  <p>However the function works, but only half of the time, sometimes it doesnt output everything it should be outputting for example if I have an array with apples, oranges, and lemons, and do an match for apples and oranges it will only print oranges or something weird. Could someone please explain to me what exactly this script does, and why it doesn't work as a substitute for <code>in_array</code>.</p>