Unexpected Loose Comparison Result

Unexpected behavior: 0 == 'string' returns true in PHP 7

Quick Answer

PHP's loose comparison operator == performs type juggling that can produce unexpected results. Use strict comparison === to compare both value and type.

Why This Happens

PHP's == operator performs type coercion before comparison. In PHP 7, 0 == 'any-string' is true because the string is coerced to 0. While PHP 8 improved this specific case, loose comparisons can still produce surprising results with mixed types. Always use === for predictable comparisons.

The Problem

$input = '0e12345'; // Looks like a string
if ($input == 0) { // True! String starting with 0e is treated as 0
    echo 'is zero';
}
if ('abc' == 0) { // True in PHP 7!
    echo 'unexpected';
}

The Fix

$input = '0e12345';
if ($input === '0') { // Strict comparison
    echo 'is zero string';
}
if ($input === 0) { // Won't match a string
    echo 'is zero integer';
}

Step-by-Step Fix

  1. 1

    Find loose comparisons

    Search for == and != operators in your code, especially where types could differ between the compared values.

  2. 2

    Switch to strict comparisons

    Replace == with === and != with !== to prevent type coercion in comparisons.

  3. 3

    Enable strict types

    Add declare(strict_types=1) at the top of each PHP file to enforce strict type checking for function calls.

Got the actual stack trace?

Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.

Explain my error

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free