3v4l.org

run code in 300+ PHP versions simultaneously
<?php $haystack = [-6, 0, 5, 10, 11, 12, 20]; $needles = [0, 3, 14, -3]; function getNearest($needle, $haystack) { if (!$haystack) { throw new Exception('empty haystack'); } $bestDistance = PHP_INT_MAX; foreach ($haystack as $value) { if ($value === $needle) { return $needle; } $distance = abs($value - $needle); if ($distance < $bestDistance) { $bestDistance = $distance; $keep = $value; } } return $keep ?? $value; // coalesc to silence potential IDE complaint } foreach ($needles as $needle) { // each test case echo "$needle -> " . getNearest($needle, $haystack) . "\n"; }

preferences:
25.33 ms | 404 KiB | 5 Q