Re: Re: A loop for the hours in a working day

From: Date: Sun, 23 Nov 2003 20:47:26 +0000
Subject: Re: Re: A loop for the hours in a working day
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-170730@lists.php.net to get a copy of this message
On Sun, 23 Nov 2003 10:49:58 -0800 (PST), you wrote: >That works, but it's a little unweildy.. especially if you want to change >the range later (changing the array may not be so bad, but then you've >got to figure out how many iterations your loops must do, etc). > >How about something like this: > >$hstart = 7; $hend = 19; $interval = 15; > >for($h=$hstart; $h < $hend; $h++) { > for($m=0; $m < 60; $m += $interval) { > echo sprintf("%d:%02d",$h,$m); } } > >Used sprintf in order to make 0 minutes display as 00. This would be a >great candidate for something to make into a function... Couple of suggestions on top: replace "echo sprintf" with a simple "printf". the above won't work across midnight, and returns time values in only one format ("hh:mm"). If I was going to bother to use a function here, I'd work with unix timestamps and strftime() (http://www.php.net/strftime) so my function would return values in pretty much any format, and at 1 second resolution. Eg: <? $now = time(); print_r (time_array ($now - 14400, $now, 15*60, '%H%M')); print_r (time_array ($now - 14400, $now, 15*60, '%I:%M %p')); function time_array ($start, $end, $interval, $format) { $output = array(); while ($start < $end) { $output [] = strftime ($format, $start); $start = $start + $interval; } return ($output); } ?> Anyone want to suggest some more embellishments? The ability to return blocks of time, maybe: "12:45 - 13:00", "13:00 - 13:15", etc.

« previous php.general (#170730) next »