Filter the array to only include items that meet your criteria.
$target = 80;
$filtered = array_filter($array, function($x) use ($target) {
return $x <= $target;
});
Then sort it, unless it's already sorted.
sort($filtered);
The greatest value <= your search target will be the last element.
$value = end($filtered);
$key = key($filtered);
To use this approach for >=
instead, just use that operator instead of <=
in the array_filter
callback, and use reset
instead of end
to get the first value rather than the last one.
This won't be ideal for large arrays that are already sorted before applying array_filter
, because array_filter
will iterate every element even after it begins to find values that don't meet the criteria. In that case it's better to just use foreach
so that you can break out of the loop as soon as you find your target.
$key = null;
$value = 0;
foreach ($array as $k => $v) {
if ($v > $target) {
break;
}
$key = $k;
$value = $v;
}
var_dump($key, $value);
For smaller arrays, or arrays that aren't already sorted, this won't make much of a difference.