PHP – Create an Array of Hours

If you need to create an array of store hours (for example), the following function can generate an associative array of values quickly, with the hours formatted and stepped (every hour, 30 mins, etc.) as you wish.

I’ve seen similar functions using DateTime(), but we’re already working with timestamps, so there’s really no need.

function get_hours_range( $start = 0, $end = 86400, $step = 3600, $format = 'g:i a' ) {

        $times = array();

        foreach ( range( $start, $end, $step ) as $timestamp ) {

                $hour_mins = gmdate( 'H:i', $timestamp );

                if ( ! empty( $format ) )
                        $times[$hour_mins] = gmdate( $format, $timestamp );
                else $times[$hour_mins] = $hour_mins;
        }

        return $times;
}

Example usage:

// use all default argument values
// 24 hours, stepped every hour, formatted as h:mm am/pm
$times = get_hours_range();

// 9-17 hours, stepped every 30 mins, formatted as hh:mm
$times = get_hours_range( 32400, 61200, 1800, 'H:i' );

Here’s the returned array, using the all the default argument values (24 hours, stepped every hour, formatted as h:mm am/pm):

Array
(
    [00:00] => 12:00 am
    [01:00] => 1:00 am
    [02:00] => 2:00 am
    [03:00] => 3:00 am
    [04:00] => 4:00 am
    [05:00] => 5:00 am
    [06:00] => 6:00 am
    [07:00] => 7:00 am
    [08:00] => 8:00 am
    [09:00] => 9:00 am
    [10:00] => 10:00 am
    [11:00] => 11:00 am
    [12:00] => 12:00 pm
    [13:00] => 1:00 pm
    [14:00] => 2:00 pm
    [15:00] => 3:00 pm
    [16:00] => 4:00 pm
    [17:00] => 5:00 pm
    [18:00] => 6:00 pm
    [19:00] => 7:00 pm
    [20:00] => 8:00 pm
    [21:00] => 9:00 pm
    [22:00] => 10:00 pm
    [23:00] => 11:00 pm
)
Find this content useful? Share it with your friends!