Svet
Svet

Reputation: 13

php long numbers in string comparison

var_dump("555555555555555555555" == "555555555555555555553"); //bool(true)
var_dump("aaaaaaaaaaaaaaaaaaaaa" == "aaaaaaaaaaaaaaaaaaaab"); //bool(false)

Why does this happen?

I know I can use

var_dump(strcmp("555555555555555555555", "555555555555555555553") == 0); //bool(false)

But why the first row returns true?

Upvotes: 1

Views: 133

Answers (2)

Naveen Kumar Alone
Naveen Kumar Alone

Reputation: 7678

In your first row

var_dump("555555555555555555555" == "555555555555555555553");

it is true

Why because, the type-coercing comparison operators will coerce both operands to floats if they both look like numbers, even if they are both already strings

This bug is discussed here

Upvotes: 1

Denis
Denis

Reputation: 5271

It's a side effect of type-coercing. There's an article on phpsadness about it. Basically, the strings in the comparison are converted to numeric types, and due to precision loss, appear to be equal.

Upvotes: 4

Related Questions