php 如何从相应的数组值中获取数组键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/2960066/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get array key from corresponding array value?
提问by JD Isaacks
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?
您可以通过其键轻松获取数组值,如下所示:$value = array[$key]但是如果我有该值并且我想要它的键呢?获得它的最佳方法是什么?
回答by Pekka
You could use array_search()to find the first matching key.
您可以array_search()用来查找第一个匹配的键。
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;
回答by Sarfraz
You can use the array_keysfunction for that.
您可以array_keys为此使用该功能。
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
这将从数组中获取键值 blue
回答by fkaufusi
$arr = array('mango', 'orange', 'banana');
$a = array_flip($arr);
$key = $a['orange'];
回答by barrycarter
No really easy way. Loop through the keys until you find array[$key] == $value
没有真正简单的方法。遍历键直到找到 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.
如果您经常这样做,请创建一个将值映射回键的反向数组/哈希。请记住,多个键可能映射到单个值。
回答by sushil bharwani
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
您的数组值可能是重复的,因此它不会为您提供确切的键。但是我认为很好的方式就像迭代并阅读密钥

