How did it happen ('-' == 0) === true?

I worked here with some exploded lines:

array_walk($data, function(&$value) { // Transform numerics into appropriate type numbers if (is_numeric($value)) { $value = substr_count($value, '.') == 1 ? (float) $value : (int) $value; } // Transform dashes into nulls if ($value == '-') { $value = null; } }); 

to convert values ​​to their respective types and some special character handling.

Where did I come across an interesting, yes, mistake?

Error

I was amazed that every record that had an initial value of string(1) '0' turned out to be null .

At first I thought the problem was with the (float) and (int) examples, but after debugging:

 var_dump((float) '0', (int) '0'); 

I saw that this is not the case that received the expected result:

 float(0) int(0) 

It took me a while to try and debug, which at the moment seemed like an obvious, weak type of check, but as soon as I did, I was shocked:

 var_dump('-' == 0); 

The above expression is as follows:

 bool(true) 

Now, when I wrote, it seemed to me that I needed to debug a few more, so:

 var_dump( '=' == 0 ); var_dump( 'What a lovely nonsense?' == 0 ); var_dump( 0 == 'DAFUQ?' ); // maybe it because of order? It PHP, world of miracles, you know... 

And each expression above is bool(true) .

Well, maybe because because internally, mystically, PHP throws an expression into (bool) ?

 var_dump( (bool) '-' == 0 ); 
<Not p> No:
 bool(false) 

So, so, so ...

I made a test script here: http://codepad.org/smiEvsDj
The problem exists in 5.2.5 (codepad), also in 5.4.3 (friend), as well as in 5.4.17 (my actual environment).

What is the cause of this function / error / what-the-F-actual-is-this ?

+6
source share
2 answers

You stumbled upon one of the main complaints people have about PHP as a language: the fact that the "==" operator is not transitive.

Any line "foo" == TRUE because the PHP people wanted this to work:

 if ($string) { // do something if $string is set } 

However, converting a string to a number (which PHP always tries to do when you use "=="), "foo" == 0 !

Of course, TRUE != 0 . This is a big pain when working with PHP, it is not logical, but it is a reality.

+2
source

It tries to parse the numbers from your strings without finding any digits and automatically returning to 0. I think ...

eg. he sees 'What a lovely nonsense?' == 0 'What a lovely nonsense?' == 0 , sees that you are comparing integers, and trying to convert What a lovely nonsense? into an integer. Since the number of digits by default is not 0, and assumes that LHS == RHS returns true

0
source

Source: https://habr.com/ru/post/951869/


All Articles