Understanding PHP Type Coercion

不想你离开。 提交于 2019-11-26 12:47:26

问题


I saw this small piece of code that is evading my understanding:

<?php

$a = \'0e462097431906509019562988736854\';
$b = \'0e830400451993494058024219903391\';

var_dump($a == $b);

Which will output:

bool(true)

I understand that when using == PHP will attempt fuzzy comparison, silently converting between types in order to perform the comparison. What I\'m not understanding is why PHP seems to think these two strings are the same. I would have thought since $a and $b are strings, that no type conversion would need to take place.

What am I not understanding?


回答1:


I think this article explains it pretty well:

Type-coercing comparison operators will convert numeric strings to numbers

Just to quote the main issue here :

According to php language.operators.comparison, the type-coercing comparison operators will coerce both operands to floats if they both look like numbers, even if they are both already strings:

where both strings are using exponential notation, hence are treated as numeric strings, making loose comparison (==), coerce these strings to floats before actually "loosely" comparing them.

As a best practice and to prevent unexpected behaviour, always try to use identity equality (===), especially when dealing with strings




回答2:


PHP attempts to convert to type float because the string begins with a 0. It stops after 0 because the next character is not a number. The same thing happens when you use type coercion to convert scientific notation to integer:

$x = (float)"12E-1x";  // $x == 1.2
$x = (int)"12E-1x";  // $x == 12 (stops at E because it's not an integer)



回答3:


It is not really an answer, but if you try:

$a = '0e4620974319065090195629887368549';
$b = '0e8304004519934940580242199033918';
echo floatval($a) . '<br>' . floatval($b);var_dump($a == $b);

You get:

0

0

bool(true)

Now, if you try:

$a = '0e4620974319065090195629887368549';
$b = '1e8304004519934940580242199033918';
echo floatval($a) . '<br>' . floatval($b);var_dump($a == $b);

You get:

0

INF

bool(false)

My guess is that PHP converts the strings to floats and gives comparison result using the floats obtained, which are not correct anyway, but that is another story.




回答4:


In the official documentation, the test of equality betwen 2 vairiables is made as follow:

$a == $b # Equal TRUE if $a is equal to $b after type juggling.

Example :

$a = 13;   # integer type
$b = "13"; # string type
var_dump($a == $b); # will say TRUE, because juggling was made
var_dump($a === $b); # will say FALSE, because PHP will also evaluate the type of variables :)


来源:https://stackoverflow.com/questions/26741378/understanding-php-type-coercion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!