phprangekeyfilteringsequential-number

Remove consecutive elements given a starting key and an ending key


I have an input array with keys representing 24-hour "military" time and values representing 12-hour "am/pm" time. I want to remove consecutive elements from my array determined by two variables that contain "military" time values.

Here are my input variables:

$starttime = '5';
$endtime = '17';
$timings = array(
     '0' => '12AM',
     '1' => '1AM',
     '2' => '2AM',
     '3' => '3AM',
     '4' => '4AM',
     '5' => '5AM',
     '6' => '6AM',
     '7' => '7AM',
     '8' => '8AM',
     '9' => '9AM',
     '10' => '10AM',
     '11' => '11AM',
     '12' => '12PM',
     '13' => '1PM',
     '14' => '2PM',
     '15' => '3PM',
     '16' => '4PM',
     '17' => '5PM',
     '18' => '6PM',
     '19' => '7PM',
     '20' => '8PM',
     '21' => '9PM',
     '22' => '10PM',
     '23' => '11PM',
);

foreach ($timings as $t) {
    
}

I would like to iterate the timings in a foreach loop, but before that, I would like to remove the timings between start time and end time.

Here my $starttime key is 5 and my $endtime key is 17.

So I would like to remove 5,6,7,8,9,10,11,12,13,14,15,16,17 from the array and keep the remaining elements.

Can some tell me how to pop those elements out?


Solution

  • Slice and Merge

    Just use array_slice and array_merge like this:

    $starttime = '5';
    $endtime = '17';
    
    $timings = array_merge(
                  array_slice($timings, 0, intval($starttime)),
                  array_slice($timings, intval($endtime) + 1)
               );
    

    Splice

    Another way which is simpler and a (insignificantly) more efficient is using array_splice. Notice that it returns the extracted array, and changes the original array, so don't place the result inside $timings.

    $starttime = '5';
    $endtime = '17';
    
    array_splice($timings,
                 intval($starttime),
                 (intval($endtime) - intval($starttime))
                );