Page 1 of 1

minimizing the number of array lookups

Posted: Sun Sep 05, 2004 4:39 am
by jasongr
Hello

Assume I have the following code:

Code: Select all

function arrayLookup($array, $key) {
  if (!array_key_exists($key, $array)) {
    return $phrase;
  }
  return $array[$key];
}
This function uses 2 array lookup to ensure that a certain key is indeed defined in an array (in case the key is indeed defined).

Is there a way to reduce the number of lookups to 1?
Here is what I would like to do:
Perform a single lookup that does the check but also gives you an index. If check if successful the second access can be done via the index to be immediate instead of going through hash table

regards
Jason

Posted: Sun Sep 05, 2004 8:49 am
by hawleyjr
why not just use the following?

Code: Select all

<?php
if(isset($arrayval[$key]))
 return $phrase;
else
return $whatever
?>

Posted: Sun Sep 05, 2004 11:15 am
by jasongr
I found a good solution with only 1 hashtable lookup

Code: Select all

$phrase= @$array[$key]; 
if ($phrase) {
  return $phrase;
}
else {
  return key;
}
Your solution isn't good because in case the $array[$key] is indeed set, then I need an additional hashtable lookup to obtain it.

Posted: Sun Sep 05, 2004 3:55 pm
by timvw
Imho his solution is better than yours.

But (afaik) the best is [php_man]array_search[/php_man]

Posted: Sun Sep 05, 2004 6:04 pm
by McGruff
Note: isset() will return false if a key is set but === null.

The original arrayLookup may be best, I think.

Incidentally, you really don't need to worry about optimising arrayLookup but if the $array parameter might be very large you can avoid copying it if you pass by ref.