PHP Reference ยท Array Functions
PHP in_array() function
Reference for PHP in_array(): test whether a value exists in an array, why strict mode matters, loose comparison traps and faster alternatives for big arrays.
The in_array() function checks whether a value exists in an array and returns true or false. It searches the values, not the keys; to test keys use array_key_exists() or isset().
By default the comparison is loose (==), which can give surprising matches. Pass true as the third argument to compare with ===, which is almost always what you want.
var_dump(in_array("b", ["a", "b", "c"])); // true var_dump(in_array(2, [1, 2, 3], true)); // true
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
in_array(mixed $needle, array $haystack, bool $strict = false): bool
| Name | Description |
|---|---|
$needle |
The value to look for. |
$haystack |
The array to search. |
$strict |
Optional. If true, uses === (same value and type). Default false uses ==. |
Return value: true if the value is found, otherwise false.
Errors / Exceptions: a TypeError if $haystack is not an array.
Usage notes
- Always pass
trueunless you want type juggling. Without it,in_array("1e1", ["10"])istruebecause both are numeric strings that compare equal. - PHP 8 changed string-to-number comparison:
0 == "abc"is nowfalse, so the old trapin_array(0, ["a"])returningtrueis gone, but numeric-string andnullsurprises remain. - It scans linearly (O(n)). For repeated checks against a large, fixed set, build a lookup with
array_flip()orarray_fill_keys()and test withisset(). - Needs the position? Use
array_search(), which returns the key orfalse. - Objects: strict mode compares object identity; loose mode compares properties.
- Beware
falsereturns fromarray_search()when testing for key 0;in_array()has no such problem since it returns a clean boolean. - To check several values, compare with
array_intersect()or loop; there is no built-in "any of" function.