How to get array key from corresponding array value?

前端 未结 5 890
-上瘾入骨i
-上瘾入骨i 2020-12-01 16:12

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条回答
  • 2020-12-01 16:33

    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

    0 讨论(0)
  • 2020-12-01 16:33

    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 讨论(0)
  • 2020-12-01 16:38

    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;
    
    0 讨论(0)
  • 2020-12-01 16:38
    $arr = array('mango', 'orange', 'banana');
    $a = array_flip($arr);
    $key = $a['orange'];
    
    0 讨论(0)
  • 2020-12-01 16:42

    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.

    0 讨论(0)
提交回复
热议问题