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?
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.
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).
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.
Usually integers are faster. If the strings are really short (one character), they might be faster.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With