I have a large-ish array of around 500 integer values. I have another integer, which I need to test against each of the values in the array to see if it meets the condition of being between the array value – 15 and the array value + 15. Other than just iterating through each value in the array and doing the comparison, is there a neater, more efficient way to do this? I’m using PHP 5.2
EDIT: So if i have array(10,…,2500) and $n = 2510, I want to see if $n matches the condition of being between 15 either side of any of the array values. In this case, the condition would be true for the last value, 2500.
I realise 500 isn’t exactly a monstrous array 🙂
The following snippet will return the values between n-15 to n+15 in the array on my run-of-the-mill desktop in less than 0.001 seconds (and that includes generating the array with values to search for):
I understood you are using PHP5.2 and cannot use the exact snippet above due to the Closure and Lambda, but that’s not the point (just use regular functions for the callbacks). The point is, if less than 0 seconds for 500 array values is not good enough in the overall scope of your application, then go ahead and write an algorithm in userland. But if less than 0 seconds is fine, then dont try to outsmart PHP.