0

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?

3 Answers 3

2
$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"

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I like this turning the array around; looks the OP is okay with it. You might be able to make it a little simpler by replacing your condition with array_key_exists. Yes, a trifle.... :)
2

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

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

Comments

1

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

1 Comment

I thought about the mirrored array approach too. It's a good one, but I'd rather just go with one array. Thanks anyway, though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.