Alex
Alex

Reputation: 9265

binary in_array search

I use a lot of in_array functions and it seems to bog down my loading times. I found the following code in the in_array php documentation. 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."

function fast_in_array($elem, $array) 
{
   $top = sizeof($array) -1;
   $bot = 0;
   while($top >= $bot) 
   {
      $p = floor(($top + $bot) / 2);
      if ($array[$p] < $elem) $bot = $p + 1;
      elseif ($array[$p] > $elem) $top = $p - 1;
      else return TRUE;
   }
   return FALSE;
}

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 in_array.

Upvotes: 3

Views: 11456

Answers (2)

Pawin Vongmasa
Pawin Vongmasa

Reputation: 91

This function does binary search. It only works if the array is sorted.

P.S. The claim that it works "five times faster" is pretty funny.

Upvotes: 5

Antimony
Antimony

Reputation: 39451

It performs a binary search, which assumes the array is in sorted total order. If the array is not sorted, it will fail.

Upvotes: 10

Related Questions