Lubje
Lubje

Reputation: 45

Comparing different strings in PHP with == returns true

I was just debugging a script and found that an if-statement wasn't working the way I expected it to.

var_dump("6064365413078728979" == "6064365413078728452");
die();

The code above will result in the following:

bool(true)

With the === operator it works as expected. Anyone got any ideas why?

I'm using PHP Version 5.3.13 with a wamp installation on a x64 windows machine.

Upvotes: 3

Views: 796

Answers (2)

Hanky Panky
Hanky Panky

Reputation: 46900

<?php
$a=6064365413078728979;
$b=6064365413078728452;
echo $a."<br>".$b;
//var_dump( $a==$b );
die();
?>

When you run that, then on your machine that might be exceeding limit for a number and that is a numeric comparison taking place. Try the script above and see value for $a will probably be different than the value you gave.

That is why when both are compared numerically they are equal. Hence use === as suggested by others

Edit: Explanation based upon @Axel's Advice.

PHP Manual explains

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

And this website is offering and explanation on the Overflow phenomenon and a small php code to test your system's integer and float range. Getting to know the limit on your servers will most probably explain it best why the offerflow occured

Upvotes: 3

&#193;xel Costas Pena
&#193;xel Costas Pena

Reputation: 6235

PHP has loose type comparison behavior, so your numerical strings are getting converted to integer types before == non strict comparison, and the conversion result is overflowing.

That is the principal reason to use === when it's possible.

Take a look at this page for further details on type juggling.

Upvotes: 7

Related Questions