Join our Newsletter — 33% off our NHI Course
Home› Guides› PHP Type Juggling Guide: Loose Comparison Flaws and…
Guide Application Security

PHP Type Juggling Guide: Loose Comparison Flaws and Strict Checks

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 11 min read
On this page

PHP's loose comparison operator converts values between types before comparing them, so a check that looks like "is this token equal to that token" can return true for values that are not the same. When the value on one side comes from a request, especially JSON that can carry numbers, booleans and arrays as well as strings, a loose comparison in an authentication, authorisation or signature check becomes a logic flaw. PHP 8.0 removed the worst number to string cases, but numeric strings, booleans, null and the loose defaults of several standard functions still behave in ways that surprise developers. This guide explains how loose and strict comparison differ, what changed in PHP 8, the flaw patterns to look for, and the fixes and tests that remove them. It is for PHP developers, code reviewers and application security engineers. Platform-wide PHP risks are in the PHP and WordPress Security Guide; this page goes deeper on comparison.

Key takeaways

  • Use === and !== for anything security relevant. The PHP manual says == compares after type juggling, while === also requires the same type, and advises strict comparison in most cases.
  • PHP 8 fixed numbers against non-numeric strings, not everything. 0 == "foo" is now false, but two numeric strings are still compared as numbers, so strings in scientific notation can compare equal to different-looking strings.
  • Standard functions default to loose matching. in_array(), array_search() and array_keys() with a search value compare loosely unless the strict argument is true, and switch compares loosely while match compares strictly.
  • Secrets need a constant-time comparison. Compare tokens, MACs and signatures with hash_equals(), and passwords with password_verify(), never with == or ===.
  • Control the type at the boundary. Validate request fields to the expected type before they reach a comparison, and add declare(strict_types=1) and static analysis rules that forbid loose comparison.

Loose vs strict comparison

PHP is dynamically typed and converts values to fit the context, which the manual calls type juggling. For comparison this means two different operators with different contracts:

OperatorNameTrue whenUse for
==EqualThe values are equal after type jugglingRarely; only when both types are known and the same
===IdenticalThe values are equal and of the same typeDefault for all comparisons, especially security checks
!= and <>Not equalThe values differ after type jugglingAvoid in security checks
!==Not identicalThe values differ or the types differDefault negative comparison
<=>SpaceshipReturns an int below, equal to or above zeroSorting; it follows the same loose rules as < and >

For loose comparison the manual sets out the order of rules. The ones that matter most for security are:

  • Bool or null against anything: both sides are converted to bool. Any non-empty string other than "0" equals true, and null, "", "0", 0 and an empty array all equal false.
  • Null against a string: null becomes "" before the comparison.
  • Two numeric strings, or a number and a numeric string: compared numerically. The manual notes the same rules apply to switch.
  • Numeric strings in scientific notation: the manual warns that a string containing the letter E bounded by digits is read as a number in scientific notation, so "0E1" == "000" is true because both are zero.
  • Arrays: compared by member count and then key by key; an array is always greater than a scalar.

A numeric string, as of PHP 8.0, is an integer or float in decimal or exponent form with optional surrounding whitespace. Leading numeric strings such as "10 items" are a separate category that raises a warning in arithmetic.

PHP 8 changes

PHP 8.0 adopted the "Saner string to number comparisons" change. The migration guide states that non-strict comparisons between numbers and non-numeric strings now cast the number to a string and compare strings, while comparisons between numbers and numeric strings work as before.

ComparisonPHP 7.xPHP 8.0 and later
0 == "0"truetrue
0 == "0.0"truetrue
0 == "foo"truefalse
0 == ""truefalse
42 == " 42"truetrue
42 == "42foo"truefalse
"1" == "01"truetrue
"10" == "1e1"truetrue
100 == "1e2"truetrue

The first six rows come from the PHP 8.0 migration guide and the last three from the comparison operators page. What did not change is the important part for reviewers: numeric string against numeric string, anything against a bool or null, and the loose defaults in standard functions. Other PHP 8 behaviour helps: arithmetic on a non-numeric string throws a TypeError instead of returning 0, and in_array() in non-strict mode now compares a non-numeric string with a number as strings. PHP 8.4 throws an Error on recursion during comparison, and PHP 8.5 makes loose comparison of non-comparable objects against booleans consistent. If you still run PHP 7.x, which no longer receives security support from the PHP project, every flaw on this page is wider.

Common flaws

These are the patterns to look for in review. They are described by shape, not as inputs to try.

Authentication and token checks

  • Loose equality on a token from JSON: code such as if ($input['token'] == $stored) trusts that the request field is a string. JSON can deliver true, a number or an array instead, and the bool and numeric rules then decide the result. The fix is a type check plus a constant-time comparison.
  • Numeric-looking hashes: hex digests that happen to match the numeric string grammar, such as a leading "0e" followed only by digits, compare as the number zero under ==. Any two such values are equal. Strict comparison or hash_equals() treats them as the strings they are.
  • Return codes compared loosely: a comparison function that returns 0 on match and null or false on error, tested with == 0, treats the error as a match. In PHP 7, passing an array to strcmp() returned null with a warning; PHP 8 throws a TypeError, but the same shape appears in custom helpers.

Authorisation and lookups

  • Allow lists with in_array(): without the third argument, true matches any truthy string and false matches "" and "0", so a role or permission check can pass for the wrong value.
  • array_search() returning 0: the first element has key 0, which is falsy. Tests such as if (!array_search(...)) treat a match at position 0 as not found, and a loose search can return a wrong key.
  • switch on user input: each case is compared loosely, so a request value can select an unintended branch. match compares strictly and throws UnhandledMatchError when no arm matches.
  • empty() and truthiness as validation: empty("0") is true, so a legitimate value is rejected or a missing value is accepted depending on how the condition is written.

Where the risk is highest

Code areaTypical loose constructImpact if wrong
Password reset, magic link and email verification tokens== between request value and stored tokenAccount takeover
API keys, webhook signatures and HMACs== or === on the digestForged requests, or timing leakage of the expected value
Role and permission checksin_array() without strict, switch on role namePrivilege escalation
Object ownership checks$row['user_id'] == $userId with mixed int and string typesAccess to another user's records
Feature flags and state machinesTruthiness tests on request valuesBusiness logic bypass

API keys and webhook secrets are non-human credentials. A loose or non-constant-time check on them affects every integration that uses the key. See the Webhook HMAC Signing vs mTLS vs IP Allowlisting guide.

Fixes

Instead ofUseWhy
$a == $b, $a != $b$a === $b, $a !== $bNo type juggling
$token === $stored for secretshash_equals($stored, $token)Constant-time; manual says the user-supplied string goes second
Comparing a password with a stored hashpassword_verify($password, $hash)The manual states it is safe against timing attacks
in_array($v, $list)in_array($v, $list, true)Identity comparison
array_search($v, $list) tested for truthinessarray_search($v, $list, true) !== falseKey 0 is a valid result
switch ($input)match ($input)Strict comparison, error on no match
empty($v) as validationExplicit checks: isset(), $v === '', is_string()"0" is not empty data

Secret comparison done right

The hash_equals() manual describes it as a timing attack safe string comparison: a normal === stops at the first differing byte, so its run time leaks how much of the secret matched. Two details matter. The known secret is the first argument and the user value the second. Both arguments must be strings of the same length; if lengths differ it returns false immediately, which can leak the length, so compare fixed-length values such as hex HMAC digests. A safe signature check computes the expected HMAC with hash_hmac(), confirms the supplied value is a string, and passes both to hash_equals(). See the Timing Attacks Guide and the Password Hashing and Key Derivation Guide.

Typed boundaries

  • Validate types first: reject a request whose token field is not a string, or whose ID is not an integer, before any comparison. filter_var() with FILTER_VALIDATE_INT or a schema validator for JSON bodies gives you known types. See the Input Validation and Output Encoding Guide.
  • Typed parameters and strict mode: the manual explains that declare(strict_types=1) applies per file, to calls made from that file, and stops scalar coercion for typed parameters. It does not change how == behaves, so it complements strict comparison rather than replacing it.
  • Normalise stored types: database drivers may return integers as strings. Cast IDs once, at the data layer, so ownership checks compare int to int with ===.

Testing

  1. Find the constructs: search the codebase for ==, !=, switch, in_array(, array_search(, array_keys( and empty(, and prioritise hits in authentication, authorisation, token and signature code. Semgrep or a similar tool can express these patterns as rules. See the Semgrep Guide.
  2. Turn on static analysis rules: the phpstan-strict-rules extension includes disallowedLooseComparison (forbids == and !=), strictFunctionCalls (requires the strict argument for in_array, array_search, array_keys with a search value and base64_decode), switchConditionsMatchingType and disallowedEmpty. PHP-CS-Fixer's strict_param rule adds the strict argument automatically and its documentation marks it risky, so review each change.
  3. Write type-confusion unit tests: for each security check, add tests that pass the wrong type (bool, integer, array, null, numeric-looking string) and assert the check fails closed. Run them on every PHP version you support.
  4. Review secret comparisons by hand: confirm every token, MAC, API key and signature comparison uses hash_equals() with the argument order from the manual, and every password check uses password_verify().
  5. Gate in CI: fail the build on new loose comparisons in security-sensitive directories, then widen the rule as legacy code is fixed. Roll back a noisy rule by scoping it to paths rather than turning it off.
  6. Measure: track loose comparisons remaining in security code (target zero), share of in_array and array_search calls with strict set, number of secret comparisons not using hash_equals(), and the share of files with declare(strict_types=1).

Small codebases can switch the whole repository to strict comparison in one pass with tests. Large legacy applications should start with authentication, session, token and payment paths, because a blanket change can alter behaviour where code genuinely relied on loose matching. See the Secure Code Review Checklist.

Framework mapping

FrameworkReferenceApplies to
OWASP ASVS 5.0V15.3.5Variables of the correct type and strict equality and comparator operations to avoid type juggling
OWASP ASVS 5.0V11.2.4Constant-time cryptographic comparisons with no short-circuit
NIST SP 800-53 Rev. 5SI-10, SA-11, SA-15Input validation, developer testing, development standards and tools
NIST CSF 2.0PR.PS-06Secure software development practices integrated in the life cycle

Practitioner checklist

  • Adopt === and !== as the coding standard and document the rare exceptions.
  • Replace every secret comparison with hash_equals(known, user) on fixed-length strings.
  • Use password_verify() for all password checks.
  • Pass true as the strict argument to in_array(), array_search() and array_keys().
  • Replace switch on request data with match.
  • Validate request field types before comparison, including JSON bodies.
  • Add declare(strict_types=1) to new files and typed parameters to security functions.
  • Enable phpstan-strict-rules or equivalent and gate new loose comparisons in CI.
  • Add wrong-type unit tests for every authentication and authorisation check.
  • Move any remaining PHP 7.x applications to a supported PHP 8 release.

Standards and references

Related NHI Mgmt Group resources: PHP and WordPress Security Guide · PHP Configuration Hardening · Timing Attacks Guide · Secure Code Review Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.