3v4l.org

run code in 300+ PHP versions simultaneously
<?php function nearest(array $arr, $needle) { $closest = current($arr); foreach ($arr as $val) { if ($val === $needle) { return $val; // found it :) } if ($val > $closest && $val < $needle) { // we found something closer and less than the needle, so use it $closest = $val; } } // we've reached the end, so return the closest solution return $closest; } $array = array(2012, 2013, 2015, 2016, 2018); $needle = "1970"; print nearest($array, $needle);

preferences:
50.36 ms | 402 KiB | 5 Q