Php Nearest minor number in array

I have an array, for example (it could be anything, but it's already ordered):

array(1,7, 12, 18, 25);

I need to find which number is closest to this array.

Taking the specified array:

$needle = 11;

The number in the array I want to get is 7. The closest number to 11should be 12, but I don't want the nearest number, I want the lowest nearest number, if that makes sense.

Other examples:

  • Enter 26, the received number should be25
  • Enter 1, the received number should be1
  • Enter 6, the received number should be1
  • Enter 7, the received number should be7
  • Enter 16, the received number should be12

I found a nice function, but it only returns the nearest number, not the lowest nearest number:

function closestnumber($number, $candidates) {
 for($i = 0; $i != sizeof($candidates); $i++) {
  $results[$i][0] = abs($candidates[$i] - $number);
  $results[$i][1] = $i;
 }
 sort($results);
 $end_result['closest'] = $candidates[$results[0][1]];
 $end_result['difference'] = $results[0][0];
 return $end_result;
}

$closest = closestnumber(8,array(1,7, 12, 18, 25));
echo "Closest: ".$closest['closest']."<br>";
echo "Difference: ".$closest['difference'];

Thanks in advance.

+3
source share
3 answers

, :

function closestnumber($number, $candidates) {
    $last = null;
    foreach ($candidates as $cand) {
        if ($cand < $number) {
            $last = $cand;
        } else if ($cand == $number) {
            return $number;
        } else if ($cand > $number) {
            return $last;
        }
    }
    return $last;
}
+2
$myArray = array(1,7, 12, 18, 25); 
$needle = 11; 

$resultKey = array_search(max(array_intersect(array_values($myArray),range(0,$needle))),$myArray); 
$result = $myArray[$resultKey];

,

$myArray = array(1,7, 12, 18, 25); 
$needle = 11; 

$result = max(array_intersect(array_values($myArray),range(0,$needle))); 
+5

Check only those candidates that are less than or equal to your number. And if you always remember only the best solution, you do not need to sort the solutions to find the best.

So try the following:

function closestnumber($number, $candidates) {
    $best = null;
    foreach ($candidates as $candidate) {
        if ($candidate <= $number) {
            if (is_null($best) || $diff > $number - $candidate) {
                $diff = $number - $candidate;
                $best = $candidate;
            }
        }
    }
    if (is_null($best)) {
        return false;
    }
    return array('closest' => $best, 'difference' => $diff);
}
+1
source

Source: https://habr.com/ru/post/1779864/


All Articles