minimizing the number of array lookups

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

minimizing the number of array lookups

Post 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
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

why not just use the following?

Code: Select all

<?php
if(isset($arrayval[$key]))
 return $phrase;
else
return $whatever
?>
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post 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.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Imho his solution is better than yours.

But (afaik) the best is [php_man]array_search[/php_man]
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post 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.
Post Reply