Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Numeric string comparison in PHP

DZone's Guide to

Numeric string comparison in PHP

· Web Dev Zone ·
Free Resource

Code something amazing with the IBM library of open source blockchain patterns. Content provided by IBM.

Although PHP's loose comparison type juggling tends to invoke some negative responses, I don't think it has really ever worked against me, and works quite comfortably in my opinion. As long as you make sure you always use strict checking (=== and !==) where you can, and fall back to the loose checks when you must.

As a PHP developer, I think it's very important to understand and memorize exactly how these work, whether you're writing new code, or maintaining existing code.

A few days ago on PHP-internals I saw a behavior that was completely new to me, and very much counter-intuitive.

    if( '20110204024217300000' == '20110204024217300264' )
    echo 'equal';
    else
    echo 'not equal';

Guess what the output is.

PHP will for loose comparisons always try to convert numeric strings, even when both sides of the comparisons are strings. Because the numbers are too big to fit in an integer, they are converted to floats. For both numbers this conversion ends up in the number: "2.0110204024217E+19" (give or take, based on the standard precision settings).

In my mind it makes sense to do this type juggling when a comparison is done with <, >, <= or >=, but it definitely feels like a bug when doing an equals check.

The moral is: always do strict checks when you are able to.

Thanks to Matt Palmear for pointing this out.

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}