php - How come ('-' == 0) === true? -


i working here exploded string walks:

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

to transform values appropriate types, , special character handling.

where stumbled upon interesting, huh, bug?

the bug

i amazed, each entry, had it's initial value string(1) '0' ended being null.

at first, thought problem relies in (float) , (int) typecasts, though, after debugging:

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

i saw that's not case, getting expected result:

float(0) int(0) 

it took me while, attempt debug the, what @ moment appeared obvious, weak type check, but, once did, shocked:

var_dump('-' == 0); 

the above expression appears be:

bool(true) 

now, while writing, thought should debug more, so:

var_dump( '=' == 0 ); var_dump( 'what lovely nonsense?' == 0 ); var_dump( 0 == 'dafuq?' ); // maybe it's because of order? it's php, world of miracles, know... 

and, every expression listed above bool(true).

okay, maybe that's because internally, mystically php casts expression (bool)?

var_dump( (bool) '-' == 0 ); 

no:

bool(false) 

so, so, so...

i made test-case here: http://codepad.org/smievsdj
problem exists in 5.2.5 (codepad), in 5.4.3 (friend) , in 5.4.17 (my actual environment).

what reason behind feature / bug / what-the-f-actually-is-this?

you have stumbled upon 1 of major complaints people have php language: fact "==" operator not transitive.

any string "foo" == true, because php people wanted work:

if ($string) {     // if $string set } 

yet, converting string number (which php tries when use "=="), "foo" == 0!

of course, true != 0. major pain when dealing php, it's not logical, it's reality.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -