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
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;
Comments
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
Pekka
Is this really what the OP is looking for? I understood it differently (as a search for a value).
Sarfraz
@Pekka: Let's what OP is looking for actually, hands up though :)
JD Isaacks
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.
Cullub
This gets all KEYS in array
$array that contain blue. Just FYI for future googlers like me.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
Michael Mrozek
I agree with making a reverse map if you need to do many lookups, but there definitely is an easy way
mmattax
@barrycarter @ Michael_Mrozek, see array_flip