简体   繁体   中英

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?

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

$key = array_search($string, $countries);
return $countries[ $key ];
$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"

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM