Why does in_array() wrongly return true with these

2020-02-16 11:52发布

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

$lead = "418176000000069007";
$diff = array("418176000000069003","418176000000057001");

if (in_array($lead,$diff))
    echo "Found";
else
    echo "Not found";

标签: php arrays
9条回答
太酷不给撩
2楼-- · 2020-02-16 12:24

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. 
查看更多
等我变得足够好
3楼-- · 2020-02-16 12:24

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))
查看更多
贼婆χ
4楼-- · 2020-02-16 12:27

It is because of the limitations of the number storage in PHP,this was a bug and is rectified and solved in newer versions of PHP.

The values exceed PHP_INT_MAX.

Try to echo/print_r $lead and $diff without using the quotes. It will result

$lead ---> 418176000000070000  
$diff ---> Array ( [0] => 418176000000070000 [1] => 418176000000060000 )

so in this case the in_array result is true!

so use strict comparison in in_array() by setting third argument in in_array() as true

     if(in_array($lead,$diff,true)) //use type too
       echo "Found";
     else
       echo "Not found";
?>

Try this. It will work.

查看更多
家丑人穷心不美
5楼-- · 2020-02-16 12:29

in_array should be stricted.

$lead = "418176000000069007";
  $diff = array("418176000000069003","418176000000057001");

  if(in_array($lead,$diff,true)) 
    echo "Found";
  else
    echo "Not found";

This problem is due to your numbers are exceeded from the defined integer limit

Note: the maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.

查看更多
SAY GOODBYE
6楼-- · 2020-02-16 12:33

Try using brackets and use strict mode:

$lead = "418176000000069007";
$diff = array("418176000000069003","418176000000057001");

if(in_array($lead, $diff, true)) {
    echo "Found";
} else {
    echo "Not found";
}
查看更多
beautiful°
7楼-- · 2020-02-16 12:36

The values exceed PHP_INT_MAX. Try doing if(in_array($lead,$diff,true)) instead.

查看更多
登录 后发表回答