PHP in_array: the strict-mode gotcha and fast lookups on large arrays
Why in_array() can return true for values that are not in the array, what changed in PHP 8, when to pass strict = true, and how to replace slow in_array() calls with isset() lookups.
On this page
in_array($needle, $haystack) returns true if the value is somewhere in the array. It looks simple, but its default comparison is PHP’s loose ==, and that produces most of the bugs. The fix is one argument:
in_array(mixed $needle, array $haystack, bool $strict = false): bool
in_array('admin', $roles, true); // always pass true unless you have a reason not to
The strict-mode gotcha
Without the third argument, in_array() compares with ==, which converts types before comparing. Some results are surprising:
in_array(null, [0]); // true: null == 0
in_array(true, ['anything']); // true: any non-empty string is truthy
in_array('1e1', ['10']); // true: both are the number 10
in_array('1', [1.0]); // true
in_array(0, ['a']); // false on PHP 8, true on PHP 7
in_array('abc', [0]); // false on PHP 8, true on PHP 7
With strict = true, the value and the type must match, like ===:
in_array(null, [0], true); // false
in_array('1', [1], true); // false: string vs int
in_array(1, [1, 2, 3], true); // true
That second line is the price of strict mode: data from a form, a URL or a CSV is always a string, so cast it first ((int) $_GET['id']) and then compare strictly.
What changed in PHP 8
PHP 8.0 changed how a number is compared with a non-numeric string. PHP 7 converted the string to a number, so 0 == 'a' was true; PHP 8 compares them as strings, so it is false. Loose in_array() calls that worked by accident on PHP 7 can behave differently after an upgrade. Check your project with the PHP upgrade checklist, and prefer strict mode so the PHP version no longer matters.
Getting the key: array_search()
To know where the value is, use array_search(). It returns the first matching key, or false, and key 0 is falsy, so compare with !==:
$key = array_search('editor', $roles, true);
if ($key !== false) {
unset($roles[$key]);
}
if (array_search(...)) is a classic bug: it fails when the match is the first element.
Arrays of arrays and objects
in_array() only looks one level deep. To check a field of every row, pull the column out first:
$users = [['id' => 7, 'name' => 'Ana'], ['id' => 9, 'name' => 'Bilal']];
in_array(9, array_column($users, 'id'), true); // true
On PHP 8.4 and later, array_any() checks a condition without building an intermediate array, and stops at the first match:
array_any($users, fn (array $u) => $u['id'] === 9); // true
For objects, strict mode compares identity (the same instance), and loose mode compares the properties of objects of the same class.
Case-insensitive search
in_array() is case-sensitive. Normalise both sides:
in_array(strtolower($tag), array_map(strtolower(...), $tags), true);
For non-English text, use mb_strtolower() so accented capitals are lowered correctly.
Performance on large arrays
in_array() checks elements one by one, so each call costs time proportional to the array size. Calling it inside a loop over another large array turns a quick job into millions of comparisons. Flip the array once, and look up keys with isset(), which takes the same time whatever the size:
$allowed = array_flip($allowedIds); // [ id => index ]
foreach ($rows as $row) {
if (isset($allowed[$row['id']])) {
// ...
}
}
On a list of 100,000 IDs, this is typically thousands of times faster than calling in_array() per row. Two caveats: keys can only be integers or strings (and numeric strings become integers, so the lookup is effectively loose), and isset() returns false for a key whose value is null. Use array_key_exists() if that matters.
If you only need to check a handful of values, or the array has a few dozen elements, in_array() with strict = true is perfectly fine and easier to read.
Checking several values at once
// Are ALL required permissions present?
$missing = array_diff($required, $granted);
$hasAll = $missing === [];
// Is ANY of them present?
$hasAny = array_intersect($required, $granted) !== [];
array_diff() and array_intersect() compare values as strings, which is usually what you want for IDs and slugs. To remove the values you do not want rather than test for them, see array_filter.