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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.