How to get array key from corresponding array value?

前端 未结 5 893
-上瘾入骨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: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;
    

提交回复
热议问题