- current: documentation ( source)
<?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 = 2000;
print nearest($array, $needle);