note 38868 added to function.in-array
| From: | mark at x2software dot net | Date: | Fri, 09 Jan 2004 15:11:45 +0000 |
| Subject: | note 38868 added to function.in-array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-63203@lists.php.net to get a copy of this message | ||
Reply/addition to melissa at hotmail dot com's note about in_array being much slower than using
a key approach: associative arrays (and presumably normal arrays as well) are hashes, their keys are
indexed for fast lookups as the test showed. It is often a good idea to build lookup tables this way
if you need to do many searches in an array...
For example, I had to do case-insensitive searches. Instead of using the preg_grep approach
described below I created a second array with lowercase keys using this simple function:
<?php
/**
* Generates a lower-case lookup table
*
* @param array $array the array
* @return array an associative array with the keys being equal
* to the value in lower-case
*/
function LowerKeyArray($array)
{
$result = array();
reset($array);
while (list($index, $value) = each($array))
{
$result[strtolower($value)] = $value;
}
return $result;
}
?>
Using $lookup[strtolower($whatyouneedtofind)] you can easily get the original value (and check if it
exists using isset()) without looping through the array every time...
----
Manual Page -- http://www.php.net/manual/en/function.in-array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+38868
Delete -- http://master.php.net/manage/user-notes.php?action=delete+38868&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+38868&report=yes
Search -- http://master.php.net/manage/user-notes.php