Short PHP code to produce hours options - php

Is there a shorter way to produce this html code with PHP?
Basically it's just a select input with hours of work options (every 30 minutes is a another option).
<select>
<option value="0" selected="selected" >From:</option>
<option value="8:00" >8:00</option>
<option value="8:30" >8:30</option>
<option value="9:00" >9:00</option>
<option value="9:30" >9:30</option>
<option value="10:00" >10:00</option>
<option value="10:30" >10:30</option>
<option value="11:00" >11:00</option>
<option value="11:30" >11:30</option>
<option value="12:00" >12:00</option>
<option value="12:30" >12:30</option>
<option value="13:00" >13:00</option>
<option value="13:30" >13:30</option>
... And so on up to 7:30 ...
<option value="7:30" >7:30</option>
</select>

This works. probably a little smaller.
while ($o <= 47) {
$date = new DateTime("08:00:00");
$date->add(new DateInterval("PT".($o*30)."M"));
echo '<option value="'. $date->format('H:i') .'" >'. $date->format('H:i') .'</option>';
$o ++;
}
The loop is fourty seven as there's 24*2 increments minus one hour.
will output the following:
<select>
<option value="08:00" >08:00</option><option value="08:30" >08:30</option><option value="09:00" >09:00</option><option value="09:30" >09:30</option><option value="10:00" >10:00</option><option value="10:30" >10:30</option><option value="11:00" >11:00</option><option value="11:30" >11:30</option><option value="12:00" >12:00</option><option value="12:30" >12:30</option><option value="13:00" >13:00</option><option value="13:30" >13:30</option><option value="14:00" >14:00</option><option value="14:30" >14:30</option><option value="15:00" >15:00</option><option value="15:30" >15:30</option><option value="16:00" >16:00</option><option value="16:30" >16:30</option><option value="17:00" >17:00</option><option value="17:30" >17:30</option><option value="18:00" >18:00</option><option value="18:30" >18:30</option><option value="19:00" >19:00</option><option value="19:30" >19:30</option><option value="20:00" >20:00</option><option value="20:30" >20:30</option><option value="21:00" >21:00</option><option value="21:30" >21:30</option><option value="22:00" >22:00</option><option value="22:30" >22:30</option><option value="23:00" >23:00</option><option value="23:30" >23:30</option><option value="00:00" >00:00</option><option value="00:30" >00:30</option><option value="01:00" >01:00</option><option value="01:30" >01:30</option><option value="02:00" >02:00</option><option value="02:30" >02:30</option><option value="03:00" >03:00</option><option value="03:30" >03:30</option><option value="04:00" >04:00</option><option value="04:30" >04:30</option><option value="05:00" >05:00</option><option value="05:30" >05:30</option><option value="06:00" >06:00</option><option value="06:30" >06:30</option><option value="07:00" >07:00</option><option value="07:30" >07:30</option></select>

For fun:
foreach(range(strtotime('8:00'), strtotime('19:30'), 1800) as $time) {
$val = date('g:i', $time);
echo '<option value="'.$val.'">'.$val.'</option>';
}
Create a range of times in 30 minute increments (1800 seconds)
Loop this range and convert the time into the correct format
Use this formatted time in your options
If you run this across a date/time in which daylight savings time is changed then it will not function correctly. You could alleviate this by setting to a timezone that does not have daylight savings time:
date_default_timezone_set('UTC');

For example:
<?php
$start = 8 * 60 * 60;
$step = 30 * 60;
$opts = '';
for ($i = 0; $i < 10; $i++) {
$time = date('H:i', $start + $i * $step);
$opt = <<<OPT
<option value="{$time}">{$time}</option>
OPT;
$opts .= $opt;
}
echo <<<OPTS
<select>
<option value="0" selected="selected" >From:</option>
{$opts}
</select>
OPTS;

You can use for loop to echo <option> tag and generating time like this.
<select>
<option value="0" selected="selected" >From:</option>
<?
$hour = 7;
$min = 30;
for ($x=0;$x < 48;$x++) {
if ($min < 30) {
$min += 30;
} else {
if ($hour < 24) {
$min = 0;
$hour += 1;
} else {
$hour = 1;
$min = 0;
}
}
$hour = sprintf("%02d", $hour);
$min = sprintf("%02d", $min);
echo '<option value="'.$hour.':'.$min.'">'.$hour.':'.$min.'</option>';
}
?>
</select>
Note 1: It is not tested and may not work properly.
Note 2: I also know, "it's not short!"
Update
I added leading zero before single digit numbers to match your format.

Related

How Display Month which is Start with Current Month Using PHP?

I want to display all month with current year but it must be start with current month like below.
I need like if current month October and year 2019 then option list should be start with 2019-10 then all renaming month with current year like below.
Output
<select>
<option value="">SELECT MONTH</option>
<option value="2019-10">October-2019</option>
<option value="2019-11">November-2019</option>
<option value="2019-12">December-2019</option>
<option value="2019-01">January-2019</option>
<option value="2019-02">February-2019</option>
<option value="2019-03">March-2019</option>
<option value="2019-04">April-2019</option>
<option value="2019-05">May-2019</option>
<option value="2019-06">June-2019</option>
<option value="2019-07">July-2019</option>
<option value="2019-08">August-2019</option>
<option value="2019-09">September-2019</option>
</select>
It's Working and give me exact output as i want.
<select>
<option value="">SELECT MONTH</option>
<?php
for ($i = 0; $i < 12; $i++)
{
$getMonth = strtotime(sprintf('%d months', $i));
$monthLabel = date('F', $getMonth)."-".date("Y");
$monthval = date("Y")."-".date('m', $getMonth); ?>
<option value="<?php echo $monthval; ?>"><?php echo $monthLabel; ?></option>
<?php }
?>
</select>
With this PHP code you can get current_month
date_default_timezone_get();
$month= date('Y-m', time());
Then you simply need to fill your 'select' tag with options in the correct order
Use the DateTime class. Create an array as follows:
$dt = date_create('first Day of this Month 00:00'); //start
$valueCaption = [];
$numberOptions = 5;
for($i=0;$i<$numberOptions;$i++){
$valueCaption[$dt->format('Y-m')] = $dt->format('F-Y');
$dt->modify('+1 Month');
}
returns a array $valueCaption how
array (
'2019-10' => "October-2019",
'2019-11' => "November-2019",
'2019-12' => "December-2019",
'2020-01' => "January-2020",
'2020-02' => "February-2020",
)
You use this array when outputting with a foreach ($valueCaption as $value => $caption) to create your options.

Generated option select time does not save properly

I have code that generates a select dropdown with times from 8:00am-6:00pm. Upon selecting an option, and saving the form, the times are saved in the database properly. HOWEVER, I cannot retrieve the times automatically. This is my code so far :
<select value="<?php echo $starttime; ?>" name="data[InvoiceTime][<?php echo $key;?>][starttime]" id="starttime_<?php echo $key+1?>" class="form-control" autocomplete="off">
<?php
$time = mktime(0, 0, 0, 1, 1);
for ($i = 28800; $i < 42600; $i += 900) { // 1800 = half hour, 86400 = one day
printf('<option value="%1$sam">%1$sam</option>',
date('g:i', $time + $i), date('g:i a', $time + $i + 1800));
}
for ($i = 43200; $i < 65000; $i += 900) { // 12pm-6pm
printf('<option value="%1$spm">%1$spm</option>',
date('g:i', $time + $i), date('g:i a', $time + $i + 1800));
}
?>
</select>
Desired output : select "9:00am" and save form 9:00am is saved to db(which happens) reload form 9:00 appears preselected due to data saved in db
Actual output : select "9:00am" and save form 9:00am is saved to db reload form 8:00am appears(default value)
The following code works, but does not generate the option values :
<select value="<?php echo $starttime; ?>" name="data[InvoiceTime][<?php echo $key;?>][starttime]" id="starttime_<?php echo $key+1?>" class="form-control" autocomplete="off">
<option value="8:00am" <?= ($item['starttime']) == '8:00am' ? 'selected' : '' ?>>8:00am</option>
<option value="9:00am" <?= ($item['starttime']) == '9:00am' ? 'selected' : '' ?>>9:00am</option>
</select>
You just needed to move your check for the value into the existing code.
However, I have simplified your code quite a bit; I'm not sure what you were trying to accomplish with your printf() statements. gmdate() is happy to work with just seconds (you don't want to use date() as it can deliver unexpected results, based on your current time zone.) If an <option> element doesn't have a value attribute, the contents are used instead, so I've removed it. You should always always separate your PHP from your HTML (ideally more than I've done here, but this is a start.)
And in case you aren't familiar with them, here is some info on the ternary statement and heredoc blocks.
<?php
$start = 28800;
$stop = 65000;
$interval = 900;
$options = "";
for ($seconds = $start; $seconds <= $stop; $seconds += $interval) {
$time = gmdate("g:ia", $seconds);
$selected = ($item["starttime"] === $time) ? " selected" : "";
$options .= sprintf("<option %s>%s</option>", $selected, $time);
}
echo <<< HTML
<select value="$starttime" name="data[InvoiceTime][$key][starttime]" id="starttime_$key" class="form-control" autocomplete="off">
$options
</select>
HTML;

Leap year friendly year/month/day select option tags with PHP embedded

I'm trying to write codes with PHP to enable leap year friendly select option tags. For example, you pick a year, then it checks if it is a leap year or not, then it shows a pull down menu (select option tags) of days preceded by another select option tags of 12 months. PHP codes are embedded in HTML. Here is my failed attempt below (I'm new to PHP):
<form method="post">
<select name="year">
<option value="" selected>Pick a year</option><!--Default-->
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<select name="month">
<option value="" selected>Pick a month</option><!--Default-->
<!--Show all 12 months-->
<?php for( $i = 1; $i <= 12; $i++ ): ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php endfor; ?>
</select>
<select name="day">
<option value="" selected>Pick a day</option><!--Default-->
<!--Show dates depending on the conditions below:-->
<?php
if ( $month == 1 || 3 || 5 || 7 || 8 || 10 || 12 )
{
//Show dates until 31
for ( $i = 1; $i <= 31; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
elseif ( $month == 2 )
{
//Leap year
if ( $year != "" && $year % 4 == 0 && $year % 100 == 0 && $year % 400 == 0 )
{
//Show dates until 29
for ( $i = 1; $i <= 29; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
//Regular year (Non-leap year)
else
{
//Show dates until 28
for ( $i = 1; $i <= 28; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
}
elseif ( $month == 4 || 6 || 9 || 11 )
{
//Show dates until 30
for ( $i = 1; $i <= 30; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
?>
</select>
<input type="submit" value="submit">
</form>
Notes:
I understand that the above is the incomplete code and it doesn't work. Besides, I don't know how to define $year or $month or $day from the select tags. Should I do it like this? If so, where should I put it?
<?php
if( $_SERVER["REQUEST_METHOD"] == "POST" )
{
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
//The rest of the php code?
}
?>
Preferably, I do not want to show years by using for loops as in months and days. I would like to do it manually this time (sorry, but if you suggest I should use the for loop, I appreciate your advise).
I wrote $year =! "" in the leap year February if block because I want to evade the empty default values from being counted.
I warmly welcome your suggestions and corrections, please help me out :)
Thanks in advance!
As far as I know about leap year:
/**
* In the Gregorian calendar 3 criteria must be taken into account to identify leap years:
* 1. The year is evenly divisible by 4;
* 2. If the year can be evenly divided by 100, it is NOT a leap year, unless;
* 3. The year is also evenly divisible by 400. Then it is a leap year.
*
* #param $year integer
* #return bool
*/
private static function isLeapYear($year)
{
// the rule was applied after 1582
if ($year > 1582) {
if (($year % 400 == 0 && $year % 100 != 0) || ($year % 4 == 0))
{
//"It is a leap year"
return true;
}
else
{
return false;
//"It is not a leap year"
}
}
return false;
}
This won't work:
( $month == 1 || 3 || 5 || 7 || 8 || 10 || 12 )
This will only check that $month == 1, then the other conditions will be evaluated to true because the integers are evaluated to true (and PHP can't compare a variable to booleans with this code).
It looks like you're trying to get the number of days per month. This can be done easily with DateTime::Format() that use the date() format:
t returns the Number of days in the given month:
$dt = new Datetime('2016-02-15');
print $dt->format('t');
// display "29"
Example.
L returns the 1 if a year is leap, 0 otherwise:
$dt = new Datetime('2016-02-15');
print $dt->format('L');
// display "1"
$dt = new Datetime('2015-02-15');
print $dt->format('L');
// display "0"
Example.
You should probably don't care about the inputs and display all the years, the 12 months and 31 days per month and check the date with checkdate() once the data have been submitted.

PHP - Displaying multiple years from the current year

I was wondering if someone could help me.
I want to display a dropdown ( select ) box with 10 years starting with the current year.
I know displaying the year is done by using
date("Y");
But im not sure how to display the 10 years after that automatically.
Any help would be greatly appreciated.
Cheers
Try:
echo('<select name="year">');
for ( $i = date("Y"); $i < date("Y")+11; $i++ )
{
echo('<option value="'.$i.'">'.$i.'</option>');
}
echo('</select>');
See result here http://codepad.viper-7.com/8S0Ogi
PHP has a slew of Date/Time functions.
One you have instantiated a DateTime Object, you'll be able to manipulate any date or time using simple date_add or date_sub functions...
However, for your situation, it would be possible and a lot simpler to simply iterate over the number of years you want in the dropdown and simply increase the value for each option.
$yearSpan = 10;
$currentYear = date("Y");
$html = '<select id="foobar">';
for($i = $currentYear; $i<=$yearSpan; $i++) {
$html .= "<option value='".$i."'>".$i."</option>";
}
$html .= '</select>';
That should populate $html with content similar to this -
<select id="foobar">
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
...
<option value="2021">2021</option>
<option value="2022">2022</option>
</select>
You can try with this:
<select>
<option>Select One</option>
<?php
$year = date("Y");
$yearto = date("Y")+10;
while ($year <= $yearto)
{
echo "<option value='".$year."'>".$year."</option>";
$year++;
}
?>
</select>

How to make PHP for loop to count down instead of up?

I am using PHP to create a dropdown box with years from 1900 to 2012. However, I'd like to have 2012 at the top of the list (i.e. count down from 2012 to 1900 instead of up from 1900 to 2012).
Any help you can provide would be great! :)
<select id="year">
<option value="">----</option>
<?
for ($i = 1900; $i <= 2012; $i++){
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
for($i = 2012; $i >= 1900; $i--)
Instead of increment, decrement the initialized value and echo the value.
for ($i = 2012; $i >=1900 ; $i--)
{
echo '<option value="'.$i.'">'.$i.'</option>';
}

Categories