Over a million developers have joined DZone.

Numeric string comparison in PHP

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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';
    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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Evert Pot, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}