Q:

PHP slice range by keys not by index

I have an array that looks like below:
$array = [
  1000 => 'something',
  2000 => 'something',
  10000 => 'something',
  20000 => 'something',
  300000 => 'something',
];

Let's say I want to get an interval between 2000 and 20000. Do I need to loop or is there a better way?
It's not an index so I can't use slice in this case.
What I'm hoping for
I could do this myself with a loop, but hopefully there is something more clever.
$range = getRange(2000, 20000, $array);
print_r($range);

Output
$range = [
  2000 => 'something',
  10000 => 'something',
  20000 => 'something',
];

A:

array_filter can filter based on the value or the key …
function getRange($min, $max, $array) {
  return array_filter($array, function($key) use ($min, $max) {
    return $key >= $min && $key <= $max;
  }, ARRAY_FILTER_USE_KEY ); // flag to pass the key into the callback function
}

