Skip to content
Tutorials Center
My learning

Topics

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.

PHP
var_dump(in_array("b", ["a", "b", "c"])); // true
var_dump(in_array(2, [1, 2, 3], true));   // true

Try it

PHP Loose versus strict comparison

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.

PHP Membership checks

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

PHP
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 true unless you want type juggling. Without it, in_array("1e1", ["10"]) is true because both are numeric strings that compare equal.
  • PHP 8 changed string-to-number comparison: 0 == "abc" is now false, so the old trap in_array(0, ["a"]) returning true is gone, but numeric-string and null surprises remain.
  • It scans linearly (O(n)). For repeated checks against a large, fixed set, build a lookup with array_flip() or array_fill_keys() and test with isset().
  • Needs the position? Use array_search(), which returns the key or false.
  • Objects: strict mode compares object identity; loose mode compares properties.
  • Beware false returns from array_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.