note 38868 deleted from function.in-array by danbrown
| From: | danbrown@php.net | Date: | Mon, 08 Jun 2009 21:46:22 +0000 |
| Subject: | note 38868 deleted from function.in-array by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-156524@lists.php.net to get a copy of this message | ||
Note Submitter: mark at x2software dot net
----
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...