Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binary in_array search

Tags:

arrays

php

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.

like image 855
Alex Avatar asked May 20 '26 08:05

Alex


1 Answers

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

like image 60
Antimony Avatar answered May 22 '26 00:05

Antimony