Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find value between array values

I have a large array and would like to find between which array values the search value would appear.

A simplified version of this array is as follows:

[0] => Array
    (
        [min] => 0
        [max] => 4.999
        [val] => low
    )

[1] => Array
    (
        [min] => 5
        [max] => 9.999
        [val] => med
    )

[2] => Array
    (
        [min] => 10
        [max] => 14.999
        [val] => high
    )

So if I was to search for 6.2 the returned result would be the array value 'med'

Is there a built in function that can easily walk over the array to make this calculation or would I need to set up a foreach loop

Thanks in advance

like image 746
Andy Gee Avatar asked Feb 14 '26 20:02

Andy Gee


1 Answers

I think a simple foreach would be fast enough, with some precaution in floating point comparisons : see it here : http://codepad.org/sZkDJJQb

   <?php

$rangeArray = array(
    array( 'min' => 0, 'max' => 4.999,  'val' => 'low'),
    array( 'min' => 5, 'max' => 9.999,  'val' => 'med'),
    array( 'min' => 10, 'max' => 14.999,  'val' => 'high'),
    );

$input = 6.2;
$precision = 0.00001 ;

foreach($rangeArray as $current)
{
  if( ($input - $current['min']) > $precision and ($input - $current['max']) <= $precision )
    {
      echo $current['val'];
      break;
    }
}

?>
like image 70
DhruvPathak Avatar answered Feb 16 '26 09:02

DhruvPathak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!