Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

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

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";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: this behavior was changed in PHP 5.4.

By default, in_array uses loose comparison (==), which means numeric strings are converted to numbers and compared as numbers. Before PHP 5.4, if you didn't have enough precision in your platform's floating-point type, the difference was lost and you got the wrong answer.

A solution is to turn on strict comparison (===) by passing an extra Boolean parameter to in_array:

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

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

Then the strings are compared as strings with no numeric coercion. However, this means you do lose the default equivalence of strings like "01234" and "1234".

This behavior was reported as a bug and fixed in PHP 5.4. Numeric strings are still converted to numbers when compared with ==, but only if the value of the string fits in the platform's numeric type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...