Create Time Slots in PHP for Given Time

In this article, we will discuss “Create Time Slots in Php”. Check the following code snippet. With this code, we can create time slots for a given interval and time range.

function getTimeSlot($interval, $start_time, $end_time)
{
    $start = new DateTime($start_time);
    $end = new DateTime($end_time);
    $startTime = $start->format('H:i');
    $endTime = $end->format('H:i');
    $i=0;
    $time = [];
    while(strtotime($startTime) <= strtotime($endTime)){
        $start = $startTime;
        $end = date('H:i',strtotime('+'.$interval.' minutes',strtotime($startTime)));
        $startTime = date('H:i',strtotime('+'.$interval.' minutes',strtotime($startTime)));
        $i++;
        if(strtotime($startTime) <= strtotime($endTime)){
            $time[$i]['slot_start_time'] = $start;
            $time[$i]['slot_end_time'] = $end;
        }
    }
    return $time;
}

 

For e.g: create time slots for 30 minutes from 10 AM to 13 PM.

$slots = getTimeSlot(30, '10:00', '13:00');
echo '<pre>';
print_r($slots);

 

Output:

Array
(
    [1] => Array
        (
            [slot_start_time] => 10:00
            [slot_end_time] => 10:30
        )

    [2] => Array
        (
            [slot_start_time] => 10:30
            [slot_end_time] => 11:00
        )

    [3] => Array
        (
            [slot_start_time] => 11:00
            [slot_end_time] => 11:30
        )

    [4] => Array
        (
            [slot_start_time] => 11:30
            [slot_end_time] => 12:00
        )

    [5] => Array
        (
            [slot_start_time] => 12:00
            [slot_end_time] => 12:30
        )

    [6] => Array
        (
            [slot_start_time] => 12:30
            [slot_end_time] => 13:00
        )

)

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

PHP
Comments (1)
Add Comment
  • Luc

    I want to generate a time slot for a doctor which is every 1 hour in Laravel but i got stuck with the code and