-1

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',
];
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

3 Answers3

3

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
}
04FS
  • 5,660
  • 2
  • 10
  • 21
2
function getRange($start,$end, $array){
  $dataArray= array();
  foreach($array as $key=>$value){

    if($key>=$start && $key<=$end){
       $dataArray[$key]= $value;
     }
  }
 return $dataArray; 
}

You will need to iterate over the array and do it manually. Even if there is any built-in function that will iterate over the result. In short, you will always need to go through the data set and you will always have a complexity of O(N).

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
0

array_splice is the solution for this. But the problem with array_splice are keys will never be preserved. Check this out for the solution array_splice preserving keys

Jonel Zape
  • 42
  • 6