Skip to content
Advertisement

Php, fill hours missing in array [closed]

I have an array composed by starting hour and finish hour. Like:

8:00 --> 9:00
9:00 --> 10:00
12:00 --> 12:30

What i need is to fill the missings hours:

8:00 --> 9:00
9:00 --> 10:00
**10:00 --> 12:00**
12:00 --> 12:30

Thanks

Advertisement

Answer

You need to iterate over the hours, and check that the las number of a loop is the same as the first number of the next loop, if not, add the interval:

<?php

# I have an array composed by starting hour and finish hour. Like:
$time_array = [
    '8:00' => '9:00',
    '9:00' => '10:00',
    // 10:00 => 12:00
    '12:00' => '12:30'
];

$last_time = '';
$new_time = [];
foreach ($time_array as $start => $end) {
    if ($last_time && $last_time != $start) {
        $new_time[$last_time] = $start;
    }
    $last_time = $end;
    $new_time[$start] = $end;
}
print_r($new_time);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement