Use PHP to Build an Array of ‘Times of Day’
It's been a long time since I posted so I find it ironic that "time" is what brings me here today. Ok that was pretty corny. You'd think this would be something that would be pretty easy to find on the web, I was a little shocked there wasn't some post about it in the PHP manual but there wasn't so here it is. I was looking for a quick way to build an array of times of day starting with midnight and increasing every half hour until 11:30 PM (or 23:30 for you G.I. Joe's). PHP has an abundance of time functions that are all very useful in their own unique way. After trying various different ones i finally came up with the following.
//build array of times. $times = array(); $time = strtotime("00:00:00"); $times["00:00:00"] = date("g:i a",$time); for($i = 1;$i < 48;$i++) { $time = strtotime("+ 30 minutes",$time); $key = date("H:i:s",$time); $times[$key] = date("g:i a",$time); } |
To break it down, I set $time to start at Midnight or 00 Hours and then set my first $times array member to the lamens "12:00 am" using the date() function. Since there are 24 hours in a day I know there are 48 half hours in a day so I set my loop to run 48 times.
Lets break down the loop:
$time = strtotime("+ 30 minutes",$time); |
This will add 30 minutes to the $time variable each time the loop runs.
$key = date("H:i:s",$time); |
This sets $key to the military notation of the current $time (the why will become more obvious later).
Finally I set my next $times array member with:
$times[$key] = date("g:i a",$time); |
Again the value of this member is set to the ordinary am/pm notation.
If you were to look at an array member in plain text it would look something like this:
$times["19:00:00"] = "7:00 pm"; |
Pretty simple, now just to display it. For my purposes I chose a select box.
<select class="required" name="CloseTime"> <option value="">--Select--</option> <?php foreach($times as $key => $value) { ?> <option value='<?php echo $key; ?>'<?php if(isset($CloseTime) && $CloseTime == $key) echo " selected='selected'"?>><?php echo $value; ?></option> <?php } ?> </select> |
Since I set up my $key as military notation I am able to use $key as the value of the <option>. I did this so I can easily put that value in the DB as a TIME and not have to worry about stripping the " am" and " pm". Alternatively since $value was set up with am/pm notation it displays nicely to the user as 7:00 PM rather than 19:00 thus allowing regular Joe to keep his fingers in his nose rather than use them to figure out what time that is.
Print This Post