user966939
user966939

Reputation: 719

Integer string comparison are equal (PHP bug?)

I'm comparing two strings like so:

<?php

$Str1 = '111122223333444455556666';
$Str2 = '111122223333444455557777';

if($Str1 != $Str2){
    // Do something
} else {
    // Do something else
}

?>

Obviously, $Str1 is not the same as $Str2, but still always executes the else-block. I know that I should simply use === or !== to compare here, but I'm wondering why (basically) any other value I try does in fact evaluate the way it's expected to.

I also read this in the documentation "If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer.", so I'm guessing it should not be below or the same as the value of PHP_INT_MAX (which is by far less than the strings I'm evaluating above) - assuming that's what they mean by "fits into". So why are the strings above being evaluated as being the same? Could it possibly be a PHP bug or is there something I'm missing?


I'm using PHP version 5.3.8 since yesterday, coming from PHP 5.3.6. Running on Windows XP.

Upvotes: 7

Views: 2218

Answers (4)

herbertD
herbertD

Reputation: 10945

Use

if (strcmp($Str1, $Str2) == 0) {
    //equal
} else {
    //not equal
}

As mentioned in https://docstore.mik.ua/orelly/webprog/php/ch04_06.htm, first compare the two as String and then compares to 0 is there're equal.

Upvotes: 1

user3104328
user3104328

Reputation: 11

One could get the thought that PHP is bit relaxed in these conversions?! Then again, do you rather want good old strict type-checking?

Not as advanced as above, but still enough to grab an hour of my time recently.

<? 
$a_var = 0;
if ($a_var=="WHATEVER")
  echo "WATCH OUT! This will be printed!";
//- as "whatever" is converted to an int

if ((string)$a_var=="WHATEVER")
  echo "OK, this will of course not be printed!";

$a_var = "0";
if ($a_var=="WHATEVER")
  echo "OK, this will of course also not be printed!";
?>

Conclusion: BEWARE of the automated casting in PHP. It may play tricks on you now and then, and bugs may be very hard to track. Explicit casting one time too many may be smarter at times, rather than relying on our great PHP understanding. ;-)

Upvotes: 1

NikiC
NikiC

Reputation: 101906

What is happening here is that the numbers are cast to floats (as they don't fit into ints) and the floats happen to be the same. See the PHP source.

This script shows that the parsed floats indeed have the same value.

Upvotes: 7

kilrizzy
kilrizzy

Reputation: 2943

That's what it looks like, if I do this:

$Str1 = '111122223333444455556666 '; 
$Str2 = '111122223333444455557777 ';

It comes out fine (note the space)

So it must be converting to number and not seeing the difference because of length

Upvotes: 1

Related Questions