9

Why does this code echo Yes. even though variables are not equal!

$a = '0e462097431906509019562988736854';
$b = '0e830400451993494058024219903391';

if( $a == $b ) echo 'Yes.';
else echo 'No!';
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • check answers here: http://stackoverflow.com/questions/14259162/comparing-different-strings-in-php-with-returns-true – Dyrandz Famador Mar 09 '15 at 05:12
  • PHP is clever/stupid enough to decide that they're hexadecimal numbers I believe. The int type probably doesn't carry that much precision on your machine (so they overflow), and the resulting values are considered equal. – alex Mar 09 '15 at 05:12
  • And lots of similar/related questions: [strcmp vs. == vs. === in PHP for checking hash equality](http://stackoverflow.com/q/14711474), [How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?](http://stackoverflow.com/q/80646), [Comparing String to Integer gives strange results](http://stackoverflow.com/q/672040), [Why does PHP consider 0 to be equal to a string?](http://stackoverflow.com/q/6843030) – mario Mar 09 '15 at 06:04

4 Answers4

8

Both will treated as numbers, and PHP had limitations in number storage before. So check that.

Try to use '==='. it will check the type also, so those will not convert to numbers.

Refer this question and its answers.

Community
  • 1
  • 1
arun
  • 3,667
  • 3
  • 29
  • 54
2

You want strcmp, not the equality operator.

rhombidodecahedron
  • 7,693
  • 11
  • 58
  • 91
2

try it, with using strcmp function:

if(int strcmp ($a,$b)===0) echo 'Yes.';
else echo 'No!';
1

Try using '===' instead of '=='.

'==' has a "weaker" comparison because it does not check for type.

'===' on the other hand, checks for the type as well, and it is generally good practice to be more explicit when you compare two things.

tzhenghao
  • 128
  • 2
  • 5