How can I find or search for the next closest larger number in an array?
For example, let’s assume the following is my array
array( 10, 8, 6, 12, 4, 20 )
when I search for 9
, it should give me 10
from the above array
if I search for 13
it should give me 20
if I search for 5
it should give me 6
and so on
2
Answers
Also figured out a new way of solving it Great to @Daniel Tharp for the great answer. What I did was to loop through each element of an array, and picked all the numbers that are bigger than the search then pushed them into a fresh new array. Finally, I used PHP
min
to get the least number from the newly created array.Be careful when using
min
as it can trigger an error if no match was found in an array. See the solution below.There’s a tradeoff in compute in sorting versus iterating over the whole thing. I’m not a compsci major and if I had to eliminate microseconds somewhere I’d benchmark this but it works fine.