Struggling with a tiny problem.
I have an array:
Array ( [0] => [6] => 6 [3] => 5 [2] => 7 )
I am checking if a set value is in the array.
if(in_array(5, $array)) { //do something } else { // do something else }
The thing is, when it find the value 5 in array, I really need the key to work with in my "do something".
In this case I need to set:
$key = 3;
(key from the found value in_array).
Any suggestions?
PHP: array_keys() function 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.
If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
array_search()
is what you are looking for.
if (false !== $key = array_search(5, $array)) { //do something } else { // do something else }
If you only need the key of the first match, use array_search()
:
$key = array_search(5, $array); if ($key !== false) { // Found... }
If you need the keys of all entries that match a specific value, use array_keys()
:
$keys = array_keys($array, 5); if (count($keys) > 0) { // At least one match... }
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