Doug
Doug

Reputation: 123

PHP add 30-minute increments to a time selection menu

Forgive me If I posted in the wrong forum or this question has been answered before. I did my research and I couldn't find an answer. I need to create a time selection menu that user can select times from in increments of 30 minutes using PHP/HTML(See image 1):

I created the time selection menu using the code below, but I don't know how to add the 30-minute increments to each time (See Image 2). Can someone please help me?

<tr><td>Time</td>
<td><select name="times" multiple>
<?php for($i = 7; $i < 20; $i++): ?>
<option value="<?= $i; ?>"><?= $i % 12 ? $i % 12 : 12 ?>:00 <?= $i >= 12 ?    'pm' : 'am' ?></option>
<?php endfor ?>
</select></td>
</tr>

Image 1 Image 2

Upvotes: 4

Views: 1578

Answers (2)

Amrinder Singh
Amrinder Singh

Reputation: 5492

this should be the better way to do this, as you have already done the main part and just wanted to add the 30 minute interval, so by using your code i am just expanding it in the following way:

<tr><td>Time</td>
<td><select name="times" multiple>
<?php for($i = 7; $i < 20; $i++): ?>

<?php if ($i % 12): ?>
    <option value="<?= $i; ?>"><?= $i % 12 ?>:00 <?= $i >= 12 ?    'pm' : 'am' ?></option>
    <option value="<?= $i; ?>:30"><?= $i % 12 ?>:30 <?= $i >= 12 ?    'pm' : 'am' ?></option>
<?php else: ?>
    <option value="<?= $i; ?>"><?= 12 ?>:00 <?= $i >= 12 ?    'pm' : 'am' ?></option>
    <option value="<?= $i; ?>:30"><?= 12 ?>:30 <?= $i >= 12 ?    'pm' : 'am' ?></option>
<?php endif; ?>

<?php endfor ?>
</select></td>
</tr>

Upvotes: 2

mayersdesign
mayersdesign

Reputation: 5310

This does the trick:

<tr><td>Time</td>
<td><select name="times" multiple>
<?php 
 $start = strtotime('07:00');
 $end   = strtotime('20:00');
 for ($i=$start; $i<=$end; $i = $i + 30*60){
   echo '<option>'.date('g:i A',$i).'</option>';
 }
?>
</select></td>
</tr>

Upvotes: 6

Related Questions