Search code examples
phpstringstring-comparisonphp-5.3

Strange Results for String comparison in PHP


We ran into an issue today that I am surprised I had not encountered before. It was related to string comparison:

echo ("9400110897799014514025" == "9400110897799014514018" ? "match" : "not");
echo ("94001108" == "94001107" ? "match" : "not");

Neither of the 2 sets matches, yet the first one reports a "match" incorrectly, while the second properly declares it "not" a match. We resolved the issue by using '===' in place of '==' but I'd really like to understand what is going on here.

Add: It's PHP 5.3


Solution

  • I tried running your code, but I got notnot in the first few attempts. Only after lowering the php version to 5.4.3 or below, I got matchnot.

    It appears you're running on an outdated version of php, and encountered this bug. It has been solved since php5.4.4.

    The best thing to do is probably to upgrade your php version (although strict comparison isn't a bad thing either way)

    Edit: According to the comments on the original answer, it looks like the problem persists in later versions as well, but only on 32bit systems.

    The problem itself comes from the fact that php is extremely loose with comparisons, converting strings that look like numbers to numbers before comparison. This leads to php considering "1e3" as equal to "1000", for example.