PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php function findValue($value, $assocArray) { $prevKey = null; foreach ($assocArray as $key => $val) { if ($value <= $key) { if ($prevKey === null) { return $val; } else { $diff1 = abs($key - $value); $diff2 = abs($prevKey - $value); if ($diff1 <= $diff2) { return $val; } else { return $assocArray[$prevKey]; } } } $prevKey = $key; } return end($assocArray); } $assocArray = [ '0' => 100, '5' => 51, '30' => 10 ]; $valueToFind = 16; $result = findValue($valueToFind, $assocArray); echo $result;
Show:  
Copy Clear