fogbound.net




Mon, 28 Mar 2016

PHP Compares Things Weirdly

— SjG @ 10:36 am

This is a known .. uh … situation, but it bit me today.

So, consider the following:
$ php --version
PHP 5.4.16 (cli) (built: Jun 23 2015 21:17:27)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
$ php -a
Interactive shell
php > $v1 = '479014103257633139480';
php > $v2 = '479014103257633139481';
php > echo ($v1==$v2?'Equal':'Not Equal');
Not Equal

Seems sane, yes? Reasonable. Kind of what you expect.

But then, consider this:

$ php --version
PHP 5.3.3 (cli) (built: Feb 9 2016 10:36:17)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
$ php -a
Interactive shell
php > $v1 = '479014103257633139480';
php > $v2 = '479014103257633139481';
php > echo ($v1==$v2?'Equal':'Not Equal');
Equal

Yeah. Let that sink in for a moment.

Some versions of PHP (before 5.4.mumble) will preëmptively convert strings to numbers before comparing them (if they contain only digits). But if the number is large enough, you may lose the precision to compare them correctly.

Wow. I mean, just … well… I dunno.

For what it’s worth, strcmp will do the right thing regardless of PHP version. But seriously. I mean. Why do I use this turdburger of a language?


One response to “PHP Compares Things Weirdly”

  1. SjG says:

    Also, take note! Functions like “in_array” use the same weird converty logic when comparing (although “in_array” has a third, $strict parameter, which makes it behave in a way that normal folks would consider sane.)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.