How can I make an array of times with half hour intervals?

Viewed 30580

I needed a list of times like so in an array...

12am
12:30am
1:00pm
...

How can I do this with PHP?

9 Answers

We can simply use strtotime to increment our time by N amount here in this case 30 minutes and date function to format it to our desired output.

$startTime = strtotime('12 am');
$endTime   = strtotime('11:59 pm');

$arrInterval = [];
while($endTime >= $startTime){
  $arrInterval[] = date("h:ia", $startTime);
  $startTime = strtotime('+30 minutes', $startTime);
}

Added index value as hour:

Here is the code:

<?php

    $time_slot= array();
        
        if ( empty( $format ) ) {
            $format = 'H:i';
        }
        $lower = 0; $upper = 86400; $step = 3600; $format = '';
        $i = 0;
        foreach ( range( $lower, $upper, $step ) as $increment ) {
            $increment = gmdate( 'H:i', $increment );
           
        
             
            $time_slot[$i] = $increment;
            $i++;
        }
    
        print_r($time_slot);

?>

Here is the result:

Array
(
    [0] => 00:00
    [1] => 01:00
    [2] => 02:00
    [3] => 03:00
    [4] => 04:00
    [5] => 05:00
    [6] => 06:00
    [7] => 07:00
    [8] => 08:00
    [9] => 09:00
    [10] => 10:00
    [11] => 11:00
    [12] => 12:00
    [13] => 13:00
    [14] => 14:00
    [15] => 15:00
    [16] => 16:00
    [17] => 17:00
    [18] => 18:00
    [19] => 19:00
    [20] => 20:00
    [21] => 21:00
    [22] => 22:00
    [23] => 23:00
    [24] => 00:00
)
Related