开发者

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?


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;


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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜