Why does in_array() wrongly return true with these (large numeric) strings?

后端 未结 9 2069
夕颜
夕颜 2020-12-08 00:35

I am not getting what is wrong with this code. It\'s returning \"Found\", which it should not.

$lead = \"418176000000069007\";
$diff = array(\"41817600000006         


        
相关标签:
9条回答
  • 2020-12-08 01:12

    If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack, and because the limit is beyond the maximum integer value.

    So if PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead. Check the PHP manuals.

    if (in_array($lead,$diff,true))
    
    0 讨论(0)
  • 2020-12-08 01:12

    From PHP Manual: String conversion to numbers:

    When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

    The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.

    As some others mentioned, you should use strict for in_array:

    bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) Searches haystack for needle using loose comparison unless strict is set.

    Some mentioned PHP_INT_MAX. This would be 2147483647 on my system. I'm not quite sure if this is the problem as the manual states:

    If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

    But floating point precision should be high enough...

    Whatever might be the "real" source of this problem, simply use strict for in_array to fix this problem.

    0 讨论(0)
  • 2020-12-08 01:18

    It's because of one defect in PHP. 418176000000069007 is modified to 2147483647 (integer limit of PHP). That is why you are getting Found.

    try in_array($lead, $diff, true)

    If the third parameter strict is set to TRUE then the in_array() 
    function will also check the types of the needle in the haystack. 
    
    0 讨论(0)
提交回复
热议问题