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?
Solution 1:
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;
Solution 2:
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
Solution 3:
$arr = array('mango', 'orange', 'banana');
$a = array_flip($arr);
$key = $a['orange'];