开发者

Better array_search()

I want to search an array 开发者_运维百科by value, not by key. It's an array of country code => country name, as below.

$countries = array (
    'AF' => 'Afghanistan',
    'AX' => 'Åland Islands',
    'AL' => 'Albania',
    'DZ' => 'Algeria',
    'AS' => 'American Samoa');

Of course, PHP's array_search() is a perfect candidate, however I don't want to return the key of the found element, but the value. The only way I can think of doing this is to use the following (from a function):

return $countries[array_search($string, $countries)];

Is there a better/faster way to do this?


$countries = array (
    'Afghanistan' => 'AF',
    'Åland Islands' => 'AX',
);
if (isset($countries[$string])){
  return $string;
}

however, nothing bad in your current way.
If I were you, I wouldn't stumble upon such a trifle "problem"


I think your one is fast enough. It's like

$key = array_search($string, $countries);
return $countries[ $key ];


You can create a mirrored array (an inverted index) and search that.

This is acceptable if your original array doesn't change often if at all, since you will have two arrays to keep in synch.

I think, though, what you basically want is a set, since you seem to be saying that if 'Algeria' is your search term, then you want to return 'Algeria'. So either build the set from the values in your array and do a lookup on that, or, if you don't want a second structure, use array_search but don't go back into the array, or use in_array().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜