PHP in_array() Function

Check if a value exists in an array

Try in_array() - edit and run
Output
bool(true)
bool(false)
bool(false)

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 match 1).

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 use isset($flipped[$value]).
  • Keys: it searches values only; use array_key_exists() or isset() for keys.

PHP in_array() FAQ

Is in_array() case-sensitive?

Yes for strings. For a case-insensitive check, compare lower-cased values: in_array(strtolower($x), array_map('strtolower', $arr)).

When should I use strict mode in in_array()?

Almost always when validating input, so that values like "0", "", null and false are not treated as equal to each other or to 0.

How do I check multiple values at once?

Use array_intersect($needles, $haystack) to get the values that are present, or !array_diff($needles, $haystack) to check that all are present.