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 can use array_keys() to get ALL the keys of an array, e.g.
The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.
As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With