PHP: How to check which item in an array is closest to a given number? - Stack Overflow

PHOTO EMBED

Wed Apr 14 2021 17:22:37 GMT+0000 (Coordinated Universal Time)

Saved by @mvieira #php

$arr = [300, 600, 900, 1200];
$number = 920;
$deltas = array_reduce(
    $arr, 
    function($t, $v) use ($number) { 
        $t[$v] = abs($v - $number); 
        return $t; 
    },
    []
);
asort($deltas);
echo array_keys($deltas)[0];
content_copyCOPY

https://stackoverflow.com/questions/30175559/php-how-to-check-which-item-in-an-array-is-closest-to-a-given-number