tags:

views:

61

answers:

4

You can easily get an array value from a key like so $value = array[$key] but if I have the value, and I want the key, whats the bet way to get it?

+6  A: 

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

Sarfraz
Is this really what the OP is looking for? I understood it differently (as a search for a *value*).
Pekka
@Pekka: Let's what OP is looking for actually, hands up though :)
Sarfraz
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.
John Isaacks
A: 

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.

barrycarter
I agree with making a reverse map if you need to do many lookups, but there definitely is [an easy way](http://stackoverflow.com/questions/2960066/best-way-to-get-array-key-from-value/2960083#2960083)
Michael Mrozek
@barrycarter @ Michael_Mrozek, see array_flip
mmattax
+3  A: 

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;
Pekka
A: 

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

sushil bharwani