What is the most efficient way to get a subarray of an array between two keys.
So for example,
$arr=array();
$arr['2014-03-01']='something';
$arr['2014-03-03']='something';
$arr['2014-02-04']='something';
$arr['2014-03-05']='something';
$arr['2014-03-07']='something';
$arr['2014-03-09']='something';
$arr['2014-01-04']='something';
$arr['2014-03-31']='something';
Get the subarray between two keys i.e. start key:2014-02-04 and end key:2014-03-07 should return an array with only:
$arr['2014-02-04']='something';
$arr['2014-03-05']='something';
$arr['2014-03-07']='something';
Is there a quick and efficient way to do this without looping through the entire array?
UPDATE: I did a benchmark here is the results:
$arr=array();
for ($i=1;$i<=1000000;$i++) {
$arr["$i"]=$i;
}
$time_start=microtime_float();
$start = '20000';
$end = '20010';
$offset = array_search($start, array_keys($arr));
$length = array_search($end, array_keys($arr)) - $offset + 1;
$output = array_slice($arr, $offset, $length);
print_r($output);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "TIME=$time\n";
echo "\n============\n";
$time_start=microtime_float();
$result = array();
$start = '20000';
$end = '20010';
foreach ($arr as $key => $value) {
if ($key >= $start && $key <= $end)
$result[$key] = $value;
}
print_r($output);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "TIME=$time\n";
exit;
RESULTS:
Array
(
[0] => 20000
[1] => 20001
[2] => 20002
[3] => 20003
[4] => 20004
[5] => 20005
[6] => 20006
[7] => 20007
[8] => 20008
[9] => 20009
[10] => 20010
)
TIME=1.8481030464172
============
Array
(
[0] => 20000
[1] => 20001
[2] => 20002
[3] => 20003
[4] => 20004
[5] => 20005
[6] => 20006
[7] => 20007
[8] => 20008
[9] => 20009
[10] => 20010
)
TIME=1.700336933136
Hence, a simple loop seems to be slightly faster. The advantage increases if I make the start further down the array. You could also use break; once the latter point is reached.