note 92460 modified in function.in-array by danbrown
| From: | danbrown@php.net | Date: | Sat, 25 Jul 2009 15:39:13 +0000 |
| Subject: | note 92460 modified in function.in-array by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158721@lists.php.net to get a copy of this message | ||
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:
<?php
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;
}
?>
--was--
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;
}
http://php.net/manual/en/function.in-array.php