What does in_array() do?
in_array() searches an array's values for $needle and returns true or false. By default it uses loose comparison (==); pass true as the third argument for strict comparison (===), which also checks the type.
Syntax
in_array(mixed $needle, array $haystack, bool $strict = false): bool
Parameters
$needle- The value to look for. String comparisons are case-sensitive.$haystack- The array to search.$strict- When true, the type must match too ("1"will not match1).
Return value
true if the value is found, otherwise false. Use array_search() if you need the key.
in_array() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Basic search
<?php
$fruits = ["apple", "banana", "cherry"];
var_dump(in_array("banana", $fruits));
var_dump(in_array("grape", $fruits));
var_dump(in_array("Apple", $fruits));
Output:
bool(true) bool(false) bool(false)
2. Loose vs strict comparison
<?php
$values = [1, 2, "3", 0];
var_dump(in_array("1", $values));
var_dump(in_array("1", $values, true));
var_dump(in_array(3, $values, true));
var_dump(in_array("abc", [0]));
Output:
bool(true) bool(false) bool(false) bool(false)
3. Whitelist validation and fast lookups
<?php
$allowedSizes = ["S", "M", "L", "XL"];
foreach (["M", "XXL"] as $size) {
echo $size . ": " . (in_array($size, $allowedSizes, true) ? "valid" : "invalid") . "\n";
}
// For many lookups, flip the array once and use isset()
$lookup = array_flip($allowedSizes);
var_dump(isset($lookup["L"]));
Output:
M: valid XXL: invalid bool(true)
Common mistakes and gotchas
- Loose comparison:
in_array("1e1", ["10"])is true because both are numeric strings equal to 10. Use strict mode for validation. - PHP 8 change:
in_array("abc", [0])was true in PHP 7 and is false in PHP 8, because non-numeric strings are no longer compared to numbers as 0. - Performance:
in_array()scans the whole array; for large arrays checked many times useisset($flipped[$value]). - Keys: it searches values only; use
array_key_exists()orisset()for keys.