Understanding PHP Type Coercion

前端 未结 4 657
梦谈多话
梦谈多话 2020-12-03 15:34

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



        
相关标签:
4条回答
  • 2020-12-03 15:57

    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 :)
    
    0 讨论(0)
  • 2020-12-03 16:05

    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

    0 讨论(0)
  • 2020-12-03 16:08

    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)
    
    0 讨论(0)
  • 2020-12-03 16:19

    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.

    0 讨论(0)
提交回复
热议问题