Fixes & guides

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
  1. The strict-mode gotcha
  2. Getting the key: array_search()
  3. Arrays of arrays and objects
  4. Case-insensitive search
  5. Performance on large arrays
  6. Checking several values at once

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.

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.

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.

Found a mistake or something out of date? Tell us and we will fix it. See our editorial policy.

A good place to start

What are you working on?

Tools, guides, PHP versions and the archive.

ToolJSON ↔ PHP arrayConvert JSON to a PHP array literal with short or array() syntax, or turn a PHP array back into JSON. Runs in your browser; nothing is uploaded.ToolSerialize / unserializeRead PHP serialized strings as a tree, repair wrong string lengths after a search-and-replace, or serialize a PHP array or JSON. Parsed safely in your browser.ToolComposer constraint testerSee exactly which versions a Composer constraint such as ^2.1, ~1.4 or >=8.1 <8.4 allows, in plain English, and test versions against it.ToolPHP date() format builderBuild a PHP date() or DateTime::format() string with a live preview in any time zone, plus a reference for every format character.ToolBcrypt generatorGenerate a bcrypt hash with a cost slider and verify a password against an existing hash. Output matches PHP password_hash() and password_verify(). Runs in your browser.ToolPHP version checkerPaste PHP code and see the minimum version it needs, the line that decided it, and any removed functions that cap the newest version it can run on.ToolCrontab generatorBuild a cron expression with presets, read it in plain English, see the next run times, and copy the crontab line or the matching Laravel scheduler call.ToolPHP upgrade checklistPick your current and target PHP versions and get every breaking change, deprecation and tooling step in between, as a checklist you can copy.GuideAllowed memory size exhaustedWhat PHP's memory_limit fatal error means, how to tell a real leak from a big job, and fixes for the usual causes: loading whole tables, unbounded arrays, Composer and recursion.GuideComposer dependency conflictsA step-by-step way to read Composer's conflict output, find the package that is blocking you, and fix it without --ignore-platform-reqs or deleting the lock file.Guidecomposer install vs updatecomposer install reproduces composer.lock; composer update rewrites it. Here is what each command does, when to use which, and a safe production deploy routine.GuideComposer uses the wrong PHP versionComposer says "your php version (8.1.x) does not satisfy that requirement" when your server runs 8.3? The cause is usually the CLI binary, config.platform.php, or platform_check.php.GuideEloquent N+1 queriesHow to spot N+1 queries in Laravel, fix them with eager loading, withCount() and constrained loads, and make Laravel throw an exception the next time one slips in.GuideHeaders already sentThe warning names the file and line that produced output. Here is how to read it, the five usual culprits (BOM, whitespace, echo, warnings, closing tags) and fixes that do not just hide it.GuideWriting a talk proposalWhat reviewers look for in a call-for-papers submission: a specific title, an abstract for attendees, notes for the committee, and a talk-sized idea. With a worked example and a checklist.GuideLaravel queue jobs not runningJobs dispatched but never processed, stuck in the jobs table, or running old code? Work through the connection, the queue name, the worker, failed jobs and deploy restarts.PHP versionsWhat's new in PHP 8.4PHP 8.4 (released 21 November 2024) brought property hooks, public private(set) visibility, new without parentheses, lazy objects, an HTML5 DOM parser and array_find(). Plus the deprecations that matter.PHP versionsWhat's new in PHP 8.5PHP 8.5 (released 20 November 2025) added the |> pipe operator, a standards-compliant URI extension, clone() with property overrides, #[\NoDiscard] and array_first()/array_last().PHP versionsWhat's new in PHP 8.6PHP 8.6 was released on 19 November 2026. Partial function application, clamp(), readonly property defaults, Io\Poll and Time\Duration, plus the session and ValueError changes to check before upgrading.GuidePHP array_filterHow array_filter() decides what to keep, why it removes "0" without a callback, how to filter by key or by key and value, and why the result needs array_values() before you treat it as a list.GuidePHP array_mapHow array_map() treats keys, how to map with the key as well as the value, what happens with several arrays or a null callback, and when a plain foreach or array_walk() is the better choice.GuidePHP array to JSONWhy json_encode() sometimes gives you an object instead of a list, how to keep floats and slashes intact, and how to catch the silent false that malformed UTF-8 returns.GuidePHP array to stringThree ways to turn a PHP array into a string, and when to use each: implode() for display and CSV-like lists, json_encode() for APIs and storage, serialize() for PHP-only data. Plus the Array to string conversion warning.GuidePHP FibersPHP 8.1 Fibers let a function pause and resume without returning. Here is how start, suspend and resume pass values, how Fibers differ from generators and threads, and where they help in real code.GuidePHP in_arrayWhy 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.GuideInterface vs abstract classInterfaces define what a class can do; abstract classes share how it is done. A side-by-side table, examples of each, the common pattern of using both, and what PHP 8.1 to 8.4 changed for interfaces.GuidePHP sort arrayWhich PHP sort function to use, in one table: by value or key, keep keys or not, ascending or descending, or with your own comparison. Plus sorting by a column, by several fields and naturally.GuideDuplicate webhooks in PHPWebhook providers retry, so the same event can arrive twice. Verify the signature, record the event ID with a unique key, answer fast and process in a queue: a pattern that works in plain PHP, Laravel and Symfony.GuidePHPStan baseline for legacy codeGenerate a PHPStan baseline, stop new errors from getting in, then raise the level step by step. A tested routine for old PHP codebases.GuidePSR-4 autoloadingHow PSR-4 maps namespaces to folders, how to configure it in composer.json, and why "Class not found" happens: case, typos, a stale autoloader or a namespace that does not match the path.GuideSerialized data broken after search-replaceChanging a domain name with SQL REPLACE() or sed corrupts PHP serialized strings because their byte lengths no longer match. Here is how to spot it and repair it safely.GuideUpgrade PHP with RectorUpgrade a PHP application one version at a time: pin the baseline, let Rector rewrite syntax, let PHPStan find what Rector cannot, and prove it with tests before you switch runtimes.PHP versionsSupported PHP versionsRelease, active support and end-of-life dates for every PHP version.ArchiveSunshinePHP talk archive 2013–2020Talk titles and speakers from eight years of the Miami PHP conference.ArchiveSpeaker indexEveryone who spoke at SunshinePHP, A to Z.