tags:

views:

115

answers:

5

What is the easiest way to code in the values in fifteen minute increments? In other words, instead of doing the following:

<select>
<option value="">12:00 AM</option>
<option value="">12:15 AM</option>
<option value="">12:30 AM</option>
<option value="">12:45 AM</option>

... so on

How could I use PHP to take up less space?

Thanks!

+1  A: 

Perhaps something like this:

for($hour = 12; $hour < 14; $hour++) {
    for ($minute = 0; $minute <= 60; $minute += 15) {
        echo '<option value="">' . (($hour > 12) ? $hour : $hour - 12) . ':' . str_pad($minute, 2, '0', STR_PAD_LEFT) . (($hour < 12) ? 'AM' : 'PM') '</option>';
    }
}
VoteyDisciple
+1  A: 

use mktime() http://us2.php.net/manual/en/function.mktime.php

for ($x = 0; $x < 10; $x++) {
 print "<option value=''>" . mktime(0, $x * 15) . "</option>";

}

Obviously your params for mktime will vary.

Rosarch
Awesome...learned something new!
+2  A: 

use the various time function there are in php:

$number = 10;

echo '<select>';
for(i = 0; i < $number; ++$i) {
  echo '<option value="">', date('h:i A', mktime(12, 15*$i)), '</option>';
}
echo '</select>';
knittl
+1  A: 

Another, well readable possibility.

$dt = new DateTime('12:00 AM');

for ($i = 0; $i < 24 * 4; $i++) {
    echo '<option value="">', $dt->format('H:i A'), '</option>';
    $dt->modify('+15 minutes');
}
Philippe Gerber
nice to see an OOP approach, but i think it's a little overkill for this example ;)
knittl
IMHO not. date_create(), date_format() and date_modify() would do just the same, but in a procedural context ... ;-)
Philippe Gerber
yes, but i'm talking about not using OOP here at all. a simple call to mktime and date will suffice. performance gain will be marginal though :D
knittl
if one tries to optimize performance on such a level one has not even understood what performance is all about ... ;-) and still: IMHO is my solution the one with the highest readability. mktime() and a bunch of obscure numbers are not very readable.
Philippe Gerber
A: 

This should do the trick.

// Start at midnight
$time = strtotime('12:00 AM');
// End one day later
$endTime = $time + strtotime('+1 day') - time();
// Print out every 15 minutes
$timeDelta = strtotime('+15 minutes') - time();

while ($time < $endTime) {
    printf('<option value="">%s</option>%s', date('h:i A', $time), "\n");

    $time += $timeDelta;
}
Sebastian P.