skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    function wpccb_get_next_closest_large_number( $search, $array ){
      $array_of_all_larger_numbers = array();
      foreach( $array as $value ){
        if( $search < $value ){
            array_push( $array_of_all_larger_numbers, $value );
        }
      }
      
      if( count( $array_of_all_larger_numbers ) == 0 ){
        return 0;
      }
      
      return min( $array_of_all_larger_numbers );
    }
    

  2. 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.

    function closest($array, $number)
    {
        sort($array);
        foreach ($array as $a) {
            if ($a >= $number) return $a;
        }
        return end($array);
    }
    
    $array = array( 10, 8, 6, 12, 4, 20 );
    
    echo closest($array, 9); // 10
    echo closest($array, 13); // 20
    echo closest($array, 5); // 6
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search