Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing String to Integer gives strange results

I'm really confused as to why this operation works. Can someone explain it?

$test1 = "d85d1d81b25614a3504a3d5601a9cb2e"; $test2 = "3581169b064f71be1630b321d3ca318f";  if ($test1 == 0)   echo "Test 1 is Equal!?"; if ($test2 == 0)   echo "Test 2 is Equal!?";  // Returns: Test 1 is Equal!? 

For clarification, I am trying to compare the string "0" to the $test variables. I already know to fix the code I can just enclose (as I should have) the 0 in ""s

I'm wondering if this is a PHP bug, a server bug, or somehow a valid operation. According to http://us3.php.net/types.comparisons this should not have worked.

Edit: Scratch that, apparently it does mention that Loose comparisons between string and 0 is true. But I still don't know why.

Edit 2: I've revised my question, why does the $test2 value of "3581169b064f71be1630b321d3ca318f" not work?

like image 494
St. John Johnson Avatar asked Mar 23 '09 02:03

St. John Johnson


People also ask

What happens if you try to compare a numeric string and a number?

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN which is always false . When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.

Can we compare string with int?

You can't compare them if you don't give specific criteria. If you want to compare their integer values, then you should convert the string to integer before comparing as you did with proper error handling (i.e. when the string is not an integer).

What is the difference between integer comparison and string comparison?

String comparison: You have to compare each of the digits one by one. This is 10 comparisons, since the integers only differ by the last digit. Integer comparison: You can do this in one comparison, saving 9 comparisons as compared to the String comparison.

Is integer comparison faster than string comparison?

Usually integers are faster. If the strings are really short (one character), they might be faster.


1 Answers

From the PHP manual:

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

like image 197
Assaf Lavie Avatar answered Oct 02 '22 03:10

Assaf Lavie