BINGO! I just tried your array_flip() suggestion, Greg. Awesome! Thanks for the tip; I wouldn't have thought of that. Ken. -----Original Message----- From: Gregory Beaver [mailto:greg@xxxxxxxxxxxxxxxxx] Sent: Monday, January 29, 2007 4:54 PM To: Ken Dozier Cc: php-general@xxxxxxxxxxxxx Subject: Re: What search algorithm does in_array() use? Ken Dozier wrote: > Does in_array() use a search algorithm (i.e., binary search), or does > it check sequentially each element in the array? > > I am using in_array() within a while{} loop to check query results > against an access-list array to produce a third array containing items > that successfully passed the comparison test. Because the two > starting arrays in the worst-case scenario can have 8,000 items each, the loop is timing out. > Advice or alternative methods are appreciated. > > Code Sample: > <?php > function check_results($results, $access_list) { # Check for $results > in array $access_list and > # add matches to array $match. > > $result = false; > $match = array(); > > while ($r = mysql_fetch_row($results)) > { if ( in_array($r[0], $access_list) ) > { $match[] = $r; } > } > > if ( count($match) > 0 ) { $result = $match; } > > return $result; > } > ?> Hi Ken, Since arrays are hash tables in PHP, it would be far faster to use an associative array. How? $access_list = array_flip($access_list); then if (isset($access_list[$r[0]])) However, this sounds more like a design issue with the SQL that creates $results. You can do the in_array natively in SQL with "WHERE otherthing IN ("thing1", "thing2",...)" which would automatically filter out the non-matches in a far more efficient manner, perhaps increasing requests per second by an exponential factor. Of course, if $access_list is from external input (user input), you will need to escape the output, make sure you have the proper encoding, etc. so you can avoid SQL injection attacks and other nastiness, but that is another topic. If you are getting $access_list from another query, you could also try using a sub-query as in "WHERE otherthing IN (SELECT ...)" but this of course assumes you are are using MySQL >= version 4.1. In any case, you are definitely going to want to revisit the design of your queries before even starting with reworking your PHP. Good luck, Greg -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php