I have an associative array in php. the keys are integers. how do i find the nearest key to any integer input?
Asked
Active
Viewed 458 times
2 Answers
1
a simple, but brute force method:
$distance = 1000000; // initialize distance as "far away"
foreach ($array as $idx => $value)
if (abs ($idx - $target_index) < $distance)
{
$distance = abs ($idx - $target_index);
$best_idx = $idx;
}

wallyk
- 56,922
- 16
- 83
- 148
0
If the array keys are in order, you can use a more efficient algorithm (which may or may not make an appreciable difference depending on what this is for and how big the arrays are):
$arr = [2 => 'a', 4 => 'b', 7 => 'c'];
$input = 5;
if (isset($arr[$input])) {
return $input;
}
foreach ($arr as $key => $value) {
if ($key > $input) {
if (prev($arr) === FALSE) {
// If the input is smaller than the first key
return $key;
}
$prevKey = key($arr);
if (abs($key - $input) < abs($prevKey - $input)) {
return $key;
} else {
return $prevKey;
}
}

FtDRbwLXw6
- 27,774
- 13
- 70
- 107