Page 1 of 1

Bizarre PHP glitch, need explanation!

Posted: Fri Oct 14, 2011 2:22 pm
by koople
I'm running this code on PHP 5.2.17, but I test on a couple other 5.2.* with the same result. The issue came along when I had an array of values and was using in_array to determine whether a specific value was present, and it kept saying a certain value was in the array that clearly was not. To recreate it simpler, I did the following test:

Code: Select all

<?php

$a = '8000112E-1268249955';
$b = '8000121E-1292539190';

// RETURNS EQUAL!!! WTF?!
if ($a == $b) {
	echo "Equal \n";
}
else {
	echo "Not Equal \n";
}


$a = '8000112E-1268';
$b = '8000121E-1292';

// RETURNS EQUAL!!! WTF?!
if ($a == $b) {
	echo "Equal \n";
}
else {
	echo "Not Equal \n";
}

$a = '8000112E-126';
$b = '8000121E-129';

// RETURNS NOT EQUAL...thank you, but why now?

if ($a == $b) {
	echo "Equal \n";
}
else {
	echo "Not Equal \n";
}


?>
Can anyone explain to me why PHP believes these 2 strings are the same? It is baffling to me. I've even tried evaluating with the idea that maybe they were being cast as hexadecimal numbers, but that doesn't make sense either. Using "===" to evaluate them DOES work correctly, but I still don't understand why just using "==". Plus the default behavior for functions like in_array is to just use "==" to compare unless the strict flag is specified, which I generally don't bother doing since nothing like this has ever been an issue before.

Re: Bizarre PHP glitch, need explanation!

Posted: Fri Oct 14, 2011 6:31 pm
by Eric!
I think strings are compared like integers. You do realize your strings are numbers with the scientific notation E? I think you are out of the range and this is throwing off the integer comparison. Integers are maxed at 9E+18 and floats are bit bigger. So I don't know how your string is being handled since it is out of range as both a integer and a float. This is probably a case of GIGO.

Maybe this will help with how php compares stuff: http://www.php.net/manual/en/types.comparisons.php

Re: Bizarre PHP glitch, need explanation!

Posted: Fri Oct 14, 2011 7:12 pm
by koople
Thank you, I did not realize that. They were not meant to be exponents just strings representing a unique code. Sometimes I like PHP's lack of need to always declare data types due to the ease of use, but I guess this is an example of why you really need to be careful or else it can introduce bugs in your code without you realizing it much later down the line.

Re: Bizarre PHP glitch, need explanation!

Posted: Fri Oct 14, 2011 7:17 pm
by Eric!
A safer way is using strcmp().