33

You can easily get an array value by its key like so: $value = array[$key] but what if I have the value and I want its key. What's the best way to get it?

5 Answers 5

70

You could use array_search() to find the first matching key.

From the manual:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
Sign up to request clarification or add additional context in comments.

Comments

18

You can use the array_keys function for that.

Example:

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

This will get the key from the array for value blue

4 Comments

Is this really what the OP is looking for? I understood it differently (as a search for a value).
@Pekka: Let's what OP is looking for actually, hands up though :)
array_search and array_keys both work for me, however array_search does take out the extra step of having to grab the first value of the array returned by array_keys. So I will use array_search, but +1 to each of you as they are both good answers.
This gets all KEYS in array $array that contain blue. Just FYI for future googlers like me.
5
$arr = array('mango', 'orange', 'banana');
$a = array_flip($arr);
$key = $a['orange'];

2 Comments

Fastest - no comparison, just flip the values with keys.
array_flip is O(n); array_search is also O(n) but it stops when it finds the value.
0

No really easy way. Loop through the keys until you find array[$key] == $value

If you do this often, create a reverse array/hash that maps values back to keys. Keep in mind multiple keys may map to a single value.

2 Comments

I agree with making a reverse map if you need to do many lookups, but there definitely is an easy way
@barrycarter @ Michael_Mrozek, see array_flip
0

Your array values can be duplicates so it wont give you exact keys. However the way i think is fine is like iterate over and read the keys

Comments

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.