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.