-1
$mostmatched = function( $input to test, $array with given values)

The array contains diffrent numbers (10,30,50 ...) and I give an input (13) and the desired function should return the nearest value in the array (10).

Is there already a function like this? Else: Any suggestions how to achieve that?

Smeaven
  • 147
  • 3
  • 14

1 Answers1

1
usort($array, function ($a, $b) use ($input) {
    return abs($input - $a) - abs($input - $b);
});
echo "Closest: $array[0]";

In other words: take the difference between $input and each value—smaller differences are closer—and sort the array by this. See https://stackoverflow.com/a/17364128/476 if this requires explanation.

Alternatively, simply loop through the array, keep track of the last smallest difference and replace it if you find a smaller difference. I'll leave the implementation of that as an exercise for the reader.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889