array_search
Searches an array for a value and returns its key.
Available since: PHP 4
Syntax
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $needle | mixed | The value to look for. |
| $haystack | array | The array to search in. |
| $strict | bool | If `true`, the type is compared as well. |
Return value
int|string|falseThe key of the first matching element, or `false` if the value is absent.
Examples
The key of a found value:
<?php
var_dump(array_search('b', ['a', 'b', 'c']));Output:
int(1)The value is not found:
<?php
var_dump(array_search('z', ['a', 'b', 'c']));Output:
bool(false)Notes
Key 0 looks like false in a loose comparison, so compare the result with === false. If you do not need the key, in_array() is simpler.
See also
- in_array — Checks whether a value exists in an array.
- array_keys — Returns all the keys of an array.
Related recipes
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.