note 15610 added to function.array-search
| From: | winter at villaweb dot net | Date: | Sun, 23 Sep 2001 02:36:03 +0000 |
| Subject: | note 15610 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-18205@lists.php.net to get a copy of this message | ||
If you can guarantee your array is sorted, here is a function that will be much faster than
array_search. If someone knows how to write this into php source to make it a pre-compiled
function, i'd apprecate if someone posted that too:
function array_binary_search($needle, $haystack, $strict)
{
$l=0;
$t=$needle;
$u=count($haystack);
$m=($l+$u)/2;
$j=0;
$k=1;
while($l <= $u)
{
$j++;
$k++;
if ( $t > $haystack[$m] )
$l = floor($m + 1);
if ( $t <= $haystack[$m] )
$u = $m - 1;
$m = ($l+$u)/2;
}
if ($haystack[$l] != $t)
return -1;
return $l;
}
http://www.php.net/manual/en/function.array-search.php