PHP if in_array() how to get the key as well?

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?


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...
}

You could just use this http://www.php.net/manual/en/function.array-search.php

$key = array_search(5, $array)
if ($key !== false) {
...

You can try

if(in_array(5, $array))
{
    $key = array_search(5, $array);
    echo $key;
}

this way you know it exists, and if it doesn't it doesn't cause notices, warnings, or fatal script errors depending on what your doing with that key there after.