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?
views:
61answers:
4
+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
2010-06-02 17:38:54
Is this really what the OP is looking for? I understood it differently (as a search for a *value*).
Pekka
2010-06-02 17:50:19
@Pekka: Let's what OP is looking for actually, hands up though :)
Sarfraz
2010-06-02 17:52:27
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
2010-06-02 18:07:21
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
2010-06-02 17:38:54
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
2010-06-02 17:41:47
+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
2010-06-02 17:39:35
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
2010-06-02 17:39:45