1

I am trying to find the value 30.33 in a range from 0 to 40 with a 0.01 step as range(0, 40, 0.01) using in_array(). All other values could be found except 30.33 and I don't know what is wrong.
This is my code:

$range = range(0, 40, 0.01);
if(in_array(30.33, $range)){
   echo 'Found';
} else {
   echo 'Not Found';
}
// returns 'Not Found'

I have also tried setting the third parameter of in_array to true but not working. Here is the code as well:

$range = range(0, 40, 0.01);
if(in_array(30.33, $range, true)){
   echo 'Found';
} else {
   echo 'Not Found';
}
// returns 'Not Found'

What I'm I doing wrong here?

2 Answers2

2

Calculations with float values are associated with inaccuracies in PHP. Your values are not exactly the same.

$range = range(0, 40, 0.01);

printf("%2.16f !=  %2.15f",$range[3033],30.33);
//30.3300000000000018 != 30.329999999999998

More on this in Compare floats in php and PHP in_array does not seem to work

jspit
  • 7,276
  • 1
  • 9
  • 17
1

Based on jspit's suggestion and answer, I finally settled on:

$min = 0;
$max = 40;
$float = 30.33;

if(($min <= $float ) && ($float <= $max)){
    echo 'Found';
} else {
    echo 'Not Found';  
}
// Found
  • When there is more than 2500 values in an array it looks like `in_array` doesnt work and that was the problem (you had 4000 values). If you look at this sandbox you can see `in_array` did work the way you originally tried but once the vallues exceeded 2500 values, `in_array` just returned a false: http://sandbox.onlinephpfunctions.com/code/1a50de51eb0410d557fa06805867b635e82038d1 – Crimin4L May 16 '21 at 04:49
  • 1
    @Crimin4L try ` foreach ($range as $i => $v) if ($v != $range1[$i + 100]) printf("%d: %2.22f != %2.22f\n", $i, $v, $range1[$i + 100]);` – greybeard May 16 '21 at 05:45