-1

I have the following

$a = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

$v = 45

I need simple way to find nearest greater/lesser elements of $v in $a

Any thoughts?

Edited

THIS IS WHY I DON'T LIKE MY THOUGHTS

<?php
    $a = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10];
    $v = 45;
    $a[] = $v;
    sort($a);
    $nearestGreater = null;
    $nearestLower = null;
    foreach ($a as $key => $val) {
        if ($val == $v) {
            $nearestGreater = (isset($a[$key + 1])) ? $a[$key + 1] : $nearestGreater;
            $nearestLower = (isset($a[$key - 1])) ? $a[$key - 1] : $nearestLower;
            break;
        }
    }
    var_dump($nearestGreater);
    var_dump($nearestLower);
    unset($a); 

This piece of shitty code is mine and is working but I need to know if is there a better solution (more simple) out there. I was NOT born with PHP book in my hands and I'm still learning. If you don't like my question skip it. I don't need your arrogant answer.
Back to the business
Anybody can IMPROVE this code to make it better to run faster? Let's suppose $a is 2000000 rows from my database.
Thank you all.

FranMercaes
  • 151
  • 1
  • 1
  • 12
  • 2
    Show us your own thoughts first ;) – Patrice Gahide Feb 01 '15 at 14:21
  • 1
    Duplicate of http://stackoverflow.com/questions/5464919/php-nearest-value-from-an-array – Gavin Simpson Feb 01 '15 at 14:22
  • I don't like my thoughts that's way I'm asking here other people thoughts . Agree or disagree... I don't care @PatriceGahide. So have a nice day. – FranMercaes Feb 01 '15 at 14:26
  • You should add them to your post even if you don't like it, because it shows that you have made an effort by yourself. That's how we do things here, even if you don't like it either. This is not a code-writing service site. Have a nice day. – Patrice Gahide Feb 01 '15 at 14:30

1 Answers1

0
function closest($array, $number) {

    sort($array);
    foreach ($array as $a) {
        if ($a >= $number) return $a;
    }
    return end($array) // or return NULL;
}

From Find number which is greater than or equal to N in an array

Community
  • 1
  • 1
Harikrishnan N
  • 874
  • 1
  • 10
  • 19