PHP if in_array() how to get the key as well?
array_search()
is what you are looking for.
if (false !== $key = array_search(5, $array)) {
// found!
} else {
// not found!
}
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...
}