PHP Reference ยท Array Functions
PHP array_search() function
Reference for PHP array_search(): find the first key of a value in an array, the false-versus-0 trap, strict mode and how to find all matching keys.
The array_search() function looks for a value in an array and returns the key of the first match, or false if the value is not found. It is the "where is it?" companion of in_array(), which only answers "is it there?".
The return value needs care: the first element of a list has key 0, which is falsy. Always compare the result with === false.
$i = array_search("b", ["a", "b", "c"]); var_dump($i); // int(1)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false
| Name | Description |
|---|---|
$needle |
The value to look for. |
$haystack |
The array to search. |
$strict |
Optional. If true, compare with ===. Default false uses ==. |
Return value: the key (integer or string) of the first matching element, or false if there is none.
Errors / Exceptions: a TypeError if $haystack is not an array.
Usage notes
- Test with
!== false.if (array_search(...))fails when the match is at key0, and""/"0"keys are falsy too. - First match only. Use
array_keys()with a filter value to get every matching key. - Use strict mode for the same reasons as
in_array(): loose comparison treats"10"and10as equal, andnullequals0and"". - Linear time. Searching a large array repeatedly is slow; build a map from values to keys once with
array_flip(). - Records: to find a row by field value, combine with
array_column(), as in the example above, or use aforeachloop andbreak. - Removing by value:
if (($k = array_search($v, $a, true)) !== false) { unset($a[$k]); }. - Only for arrays; for strings use
strpos()orstr_contains().