Hi! Could we please enable some services and cookies to improve your experience and our website?

PHPize Online / SQLize Online  /  SQLtest Online

A A A
Login    Share code      Blog   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear

Stuck with a problem? Got Error? Ask AI support!

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 = 23; $result = findValue($valueToFind, $assocArray); echo $result; // Выведет 51
Copy Clear