3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?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 = 2011; print nearest($array, $needle);
Output for 5.3.7 - 7.1.0
2012