JD Isaacks
JD Isaacks

Reputation: 58014

How to get array key from corresponding array value?

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?

Upvotes: 33

Views: 58032

Answers (5)

mana
mana

Reputation: 1239

$arr = array('mango', 'orange', 'banana');
$a = array_flip($arr);
$key = $a['orange'];

Upvotes: 5

Sarfraz
Sarfraz

Reputation: 382881

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

Upvotes: 18

sushil bharwani
sushil bharwani

Reputation: 30207

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

Upvotes: 0

Pekka
Pekka

Reputation: 449803

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;

Upvotes: 70

user354134
user354134

Reputation:

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.

Upvotes: 0

Related Questions