Anti Veeranna

The pain, the pleasure ..

PHP type juggling

with one comment

Given the following piece of PHP code:

$a = '1112000000001779149';
$b = '1112000000001779148';
var_dump($a == $b);

Can you tell, without trying to run it, what the result is?

The answer – it depends on your platform. On a 64bit platform you will get boolean false, on a 32bit platform you will get boolean true.

Why? Because PHP does type juggling, if strings are compared and they look like numbers, then they will be convereted to numbers before doing the comparision. And the following piece of code demonstrates the behaviour:

print php_uname('m');
print "\n";
print PHP_INT_SIZE;
print "\n";
print (int)1112000000001779149;
print "\n";

If you run it on different platforms, then this is the result that you will get:

x86_64
8
1112000000001779149

i386
4
-1

From this its already obvious, why the above string comparision resulted in true on 32bit platform. Its because -1 indeed equals -1.

Solution?

Either use === for comparisions, or if you care about your numbers, use the bcmath extension

Advertisement

Written by Anti Veeranna

2009/12/12 at 14:13

Posted in Pain

Tagged with

One Response

Subscribe to comments with RSS.

  1. [...] Previously. [...]


Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.