3

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

1 Answer 1

6

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;
    }
}

?>
Sign up to request clarification or add additional context in comments.

1 Comment

It certainly did the trick, it was the break; that I'd forgotten to use and it's a very large array! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.