129 points · by moe · 14y ago · 138 comments
We've got gigabytes of RAM and terabytes of storage to work with; don't throw away characters in a string just because they don't fit in a compact data type used only because there is a passing resemblance of one to the other.
If I'm comparing two 53-digit barcodes, and they differ only by the last digit (checksum), then it's very important that comparing those two STRINGS comes up FALSE.
Then use === and do a type-strict comparison.
<?php
// Prints bool(true)
var_dump('9223372036854775807' == '9223372036854775808');
// Prints bool(false)
var_dump('9223372036854775807' ==='9223372036854775808');And BTW, things that work in most cases, but not all cases, are exactly where bugs come from.
If I didn't have such a low pain tolerance, I would get that tattooed on my body somewhere prominent.
What is shown here is just a rare edge case that you should not normally encounter.
But I think that == has some other behaviors which are really detrimental. Like 0 == 'hallo world'. Sadly those can't be fixed due to backwards compatibility.
This is what continually baffles me about PHP. There are plenty of bad languages out there, but PHP seems pretty much unique in having a community that actively resists any improvement and actively campaigns to keep the broken stuff around.
"...My 5cents on that (recently published issues):
<? if ('9223372036854775807' == '9223372036854775808') { echo "I can not count!\n"; } ?> (see https://bugs.php.net/bug.php?id=54547)
or
built-in PHP web server dies with a large Content-Length header value: The value of the Content-Length header is passed directly to a pemalloc() call in sapi/cli/php_cli_server.c on line 1538. The inline function defined within Zend/zend_alloc.h for malloc() will fail, and will terminate the process with the error message "Out of memory". (see https://bugs.php.net/bug.php?id=61461) Luckily we are getting Javascript ready to replace all PHP on the server sooner or later ;-)..."
If you compare a number with a string or the comparison
involves numerical strings, then each string is converted
to a number and the comparison performed numerically.I'm currently working with barcodes: numerical strings from 6 to 55 digits. In no way can I risk having one barcode be evaluated as equal to a literally different barcode just because the symbols in that string just happen to exhibit a passing resemblance to data of a different type.
Again, it's not just that it has loose typing. It's that it's taking what is OBVIOUSLY a string, converting it to an integer, THEN converting it to yet another data type which imposes data loss.
Intolerable for real-world use. A toy language. Alas, PHP, we hardly knew you...
ETA: Oh, I'd love to know the justification for the downvoting.
I was about to give an outraged reply that, if PHP is like Perl, then it doesn't scan the string afresh, just keeps a flag indicating whether or not it thinks a string is numeric. However, it turns out that's not true at all. `Perl_looks_like_number`, defined in `sv.c`, calls `Perl_grok_number`, defined beginning on l. 577 (as of v5.14.2) in `numeric.c`, which (after some book-keeping) does this:
if (s == send) {
return 0;
} else if (*s == '-') {
s++;
numtype = IS_NUMBER_NEG;
}
else if (*s == '+')
s++;
if (s == send)
return 0;
if (isDIGIT(*s)) {
UV value = *s - '0';
if (++s < send) {
int digit = *s - '0';
if (digit >= 0 && digit <= 9) {
value = value * 10 + digit;
if (++s < send) {
digit = *s - '0';
if (digit >= 0 && digit <= 9) {
value = value * 10 + digit;
if (++s < send) {
digit = *s - '0';
if (digit >= 0 && digit <= 9) {
value = value * 10 + digit;
and goes on and on and on and on in the same vein. Sheesh! (I didn't forget to close that last brace; the next line is de-dented, but that seems to be a mistake.)Seems like a silly thing to say. I wouldn't write avionics software with it, but there are a billion websites demonstrating that it's pretty decent for real-world use. At least as good as any other language, I'd guess.
I'm sorry, I would like that to be true, but programmers rarely are half as smart as they think they are. We have many more years of PHP and its resulting insanity ahead of us.
Have you been out on the internet the past decade? Do you have a tendency to make extremities of things and trying to stand the needle on its tip?
Making extremes? My medical application would fail FDA approval in minutes if ported to PHP precisely because of this issue.
Edit: I know == is not a string comparison. But you'd expect it to fail in a predictable way when passed strings that are not parseable as numbers, instead of trying to fall back on a string comparison so that people get the wrong idea.
I generally avoid exceptions/error_levels in all languages but this is probably a good cause for them, in order to keep the rest backwards compatible.
In this case in php, the truncation happens due to loss of precision in the mantissa of the double precision float. But there are so many other ways to lose precision, I don't think it's reasonable to ask a language to attempt to account for them.
This is why languages should have clear rules about when type conversion occurs, and allow the user to prevent it when it isn't desirable.
edit: in fact, amusingly, php seems to be doing some non-standard stuff with its floats. I was going to make a point about how you can't determine if a double is a "correct" representation of a string decimal, but in mocking an example I discovered something odd. Check this out:
This is what one should expect:
$ ruby -e'puts "%5.25f" % 0.1'
0.1000000000000000055511151
$ perl -wle'printf "%5.25f\n", 0.1'
0.1000000000000000055511151
But in php:
$ php -r'printf("%5.25f\n", 0.1);'
0.1000000000000000000000000
$ php -r'printf("%5.25f\n", "0.1");'
0.1000000000000000000000000
Is php changing the type conversion? Or not using double precision at all?
[1] This doesn't really happen in PHP, but you have $php_errormsg that can be set without stopping execution (as happens with some errors/warnings when error_level is not set to E_STRICT, and below that depending on the error). This errors could be triggered in a new level, let's say "E_PEDANTIC".
This reminds me of Excel-like programs that by default, automatically detect (and convert) fields that appear to be dates/strings...often to catastrophic effect.
Prelude> "9223372036854775807" == "9223372036854775808"
False
Prelude> "9223372036854775807" == 9223372036854775808
<interactive>:1:25:
No instance for (Num [Char])
arising from the literal `9223372036854775808'
at <interactive>:1:25-43
Possible fix: add an instance declaration for (Num [Char])
In the second argument of `(==)', namely `9223372036854775808'
In the expression: "9223372036854775807" == 9223372036854775808
In the definition of `it':
it = "9223372036854775807" == 9223372036854775808
Prelude>
Yes. Strings are not numbers.(This is not strictly required, of course; you can write a typeclass that defines a two-paramater ==, instead of a -> a -> Bool, it could be a -> b -> Bool. But that's dumb, so nobody does.)
One of the worst bugs I've encountered years ago involved the conversion of Javascript int from string to number. Javascript's long integer has only 53 bits, while most other languages have 64-bit long int. When the backend language generated Javascript snippets (JSON) containing integers greater than 53 bits, the horror started at the frontend. Javascript happily truncated the int to 53 bits upon conversion from string to int. It was not a happy tale since those long integers were account numbers. The wrong accounts ended up getting updated, randomly at first appearance.
This is easily solved by using the type-checking === operator, which exists for that purpose.
I hesitate to say that this is a feature, not a bug, but it is clear that this is documented behavior.
(Such that
strcmp('9223372036854775807', '9223372036854775808');
returns -1, meaning the strings are not equal.) php > var_dump('9223372036854775807' == '9223372036854775808');
bool(true)
php > var_dump('9223372036854775807' === '9223372036854775808');
bool(false)Here is what node.js says:
> "9223372036854775807" == "9223372036854775808"
false>>> "9223372036854775807" == "9223372036854775808" false
>>> 9223372036854775807 == "9223372036854775808" true
>>> 9223372036854775807 == 9223372036854775808 true
I believe the grandparent post is more referring to "general" use cases then this one. Personally I now default to strict comparison operators both in JS and PHP unless I explicitly want a loose comparison and end up missing most of these strange vagaries these days.
The one case where I sometimes use == is if I want to check for "null" or "undefined". Even then it scares me.
Its the fact PHP refuses to fix it that is the news.
This is what ghci (Haskell) says:
Prelude> 9223372036844775807 == 9223372036844775808
False
Prelude> 9223372036844775807.0 == 9223372036844775808.0
True
This is what Python says: >>> 9223372036844775807 == 9223372036844775808
False
>>> 9223372036844775807.0 == 9223372036844775808.0
True
Here is what SBCL (Common Lisp) says: * (= 9223372036844775807 9223372036844775808)
NIL
* (= 9223372036844775807.0 9223372036844775808.0)
T
Lua: > print(9223372036844775807 == 9223372036844775808)
true (!!!!!)
> print(9223372036844775807.0 == 9223372036844775808.0)
true
Javascript: alert(9223372036844775807 == 9223372036844775808)
true (!!!!!)
alert(9223372036844775807.0 == 9223372036844775808.0)
true
Other languages that will also do this[1]: Javascript, Lua. Languages that won't: anything with actual, honest-to-god integers, and not floats or doubles masquerading as them.[2] Languages that actually handle numbers sensibly: Lisp.[3] I'm not familiar with any others that actually treat rational numbers like rational numbers, but I expect there are some. (It's still, of course, impossible to treat real numbers like real numbers, meaning that this sort of thing will also happen there.)[1] Well, not the string-to-number bit, but whatever.
[2] Except for the niggle that they'll still do this when you're using floating point numbers, because this is what floating point numbers do.
But it seems to me - and let me stress that I am not a PHP developer and won't be bothered to install PHP on my machine at this time - that PHP is failing to exhibit exactly the behavior your code examples are giving.
Put it another way - type coercion 'run amok' being another thing entirely, you are correct that this bug stems from the fact that PHP is converting these integers to floating-point, and the standard floating point implementations will all behave in this exact way (thus, not a PHP bug.)
However, the issue here is that (again, "most?") languages also provide an easy way to get to arbitrary-precision arithmetic - and indeed, in the three examples you posted, you simply encode in the most natural way (by simply writing them) the two integers and they automatically compare correctly.
My understanding is that this is not the case in PHP, and that is a shame.
If you're going to run with PHP's axioms, then the specifications should (1) demand an unlimited-length integer type, and (2) NEVER convert a non-lossy to lossy data type without very good overt reason.
Fail.
#include <stdio.h>
#include <stdlib.h> /* strtol, strtod */
/* Convert string to long and return true if successful. */
int string_long(char *beg, long *num)
{
char *end;
*num = strtol(beg, &end, 10);
return *beg != '\0' && *end == '\0';
}
int main(void)
{
char *x_str = "9223372036854775807";
char *y_str = "9223372036854775808";
long x;
long y;
int x_ok = string_long(x_str, &x);
int y_ok = string_long(y_str, &y);
printf("x_str = %s\n", x_str);
printf("y_str = %s\n", y_str);
printf("x = %ld (ok=%d)\n", x, x_ok);
printf("y = %ld (ok=%d)\n", y, y_ok);
printf("x and y are %s\n", x == y ? "equal" : "not equal");
return 0;
}
And here's the output: x_str = 9223372036854775807
y_str = 9223372036854775808
x = 9223372036854775807 (ok=1)
y = 9223372036854775807 (ok=1)
x and y are equal
I compiled it like so: gcc -c -Wall -Werror -ansi -O3 -fPIC src/test_num.c -o obj/test_num.o #include <stdio.h>
int main(void)
{
long x = 9223372036854775807;
long y = 9223372036854775808;
printf("x = %ld\n", x);
printf("y = %ld\n", y);
printf("x and y are %s\n", x == y ? "equal" : "not equal");
return 0;
}
The error message is: gcc -c -Wall -Werror -ansi -O3 -fPIC src/test_num2.c -o obj/test_num2.o
src/test_num2.c: In function ‘main’:
src/test_num2.c:6:11: error: integer constant is so large that it is unsigned [-Werror]
src/test_num2.c:6:2: error: this decimal constant is unsigned only in ISO C90 [-Werror]
cc1: all warnings being treated as errorsIf you don't actually use PHP (as most of the commenters seem not to) don't comment on the bug, it has nothing to do with you and you are just making noise.
But the problem in my perception is that it is very error-prone. A less error-prone solution would be only convert one string value to number when the another is really a number. For example:
'9223372036854775807' == 9223372036854775808
That is, in fact, exactly how JS handles it.
9223372036854775807 == 9223372036854775808
true
9223372036854775807 === 9223372036854775808
true
> 9223372036854775807 == 9223372036854775808
true
> 9223372036854775807 === 9223372036854775808
true
However, that is not the two lines written about in this post. The following works as one would expect on JS, but (I assume, based on the report) not in PHP: > "9223372036854775807" == "9223372036854775808"
false
> "9223372036854775807" === "9223372036854775808"
false