Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can only make this more efficient if you add some more information into the mix, by sorting the array or similar. otherwise you can only compare every value. but 500 is not a lot.</p> <p>if you sort the array then you could improve performance in several ways, like looking at each value to see if it is within the range and stopping when you find the first one that is not (small improvement probably). Or you could search for the first element which is in range and the first element which is out of range and then you know the indices of the valid elements and can just use those.</p> <p>you could find the indices of interest using a <a href="http://en.wikipedia.org/wiki/Binary_search_algorithm" rel="nofollow">binary search</a> which will be quicker than looking at each value.</p> <p>Obviously the benefits of doing this depend on the context, as phant0m pointed out in the comments, if you are going to sort the array once for each comparison, then you may as well not bother, and just do the comparison. If you are going to look in the same array for many different comparison values then sorting may benefit you. If you can create the array already sorted at no extra cost, then its a win-win situation.</p> <p>a binary search over an array of 500 elements will take about 8 searches. If you only need to find if one of the values matches your condition or not then this will be much more efficient. if you need to find all the values which do, then you'll need to do a bit of modification to find the first value which is within it and the last, but it should still come out at &lt;25 comparisons rather than 250 (average comparisons of your sorted array doing it sequentially). but the benefits will be more noticable the bigger the array, as there will be some overhead in working out the next search point etc...</p> <p><a href="http://www.roseindia.net/tutorial/php/phparray/binarysearch.html" rel="nofollow">Here is an example of binary search in PHP</a>, this is just a google result, not checkd or verified by me, and will need tweaking to allow for your range condition.</p> <p><a href="http://terenceyim.wordpress.com/2011/02/01/all-purpose-binary-search-in-php/" rel="nofollow">this one</a> might be better and might allow you to provide a comparer which will test for the range you want.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload