Understanding PHP Type Coercion

给你一囗甜甜゛ 提交于 2019-11-27 05:20:39

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

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)

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.

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