Jump to content

[SOLVED] Search for range in array


tippy_102

Recommended Posts

I have an array of prices and I want to return an array that contains all prices between two values.

 

example: $test = array('2.50','2.75','3.25','3.70','8.45','9.20','9.45');

 

Say I wanted to grab all prices between 3.00 and 9.00

Is there a way to do this without walking through each value and testing for greater and less than?

Link to comment
https://forums.phpfreaks.com/topic/141176-solved-search-for-range-in-array/
Share on other sites

Well, I can think of one way where you would only have to test "some" of the values. Don't know how efficient this would be.

 

function includedValues($array, $min, $max)
{
    sort($array, SORT_NUMERIC);

    //Remove values less than the min
    while($array[0]<$min)
    {
        array_shift($array);
    }

    //Remove values greater than the max
    while($array[count($array)-1]>$max)
    {
        array_pop($array);
    }

    return array;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.