[PHP] Sample to automatically generate select option tags from the latest year back to the past 100 years
A sample program to output a select box from the latest year back to 100 years ago with PHP, and
We'll introduce patterns such as setting a specific year as the initial value.
The JavaScript version is introduced in the article below.
<select>
<?php
$dateY = (int) date('Y');
$past = 100; //年前まで
for($i = 0; $i < $past; ++$i):
$year = $dateY - $i; ?>
<option value="<?= $year; ?>"><?= $year; ?></option>
<?php endfor; ?>
</select>
How about this for recruitment sites, etc.?
If your target audience is somewhat defined, let's make such considerations!
<select>
<?php
$dateY = (int) date('Y');
$past = 100; //年前まで
$select = 22; //年前を初期値に
for($i = 0; $i < $past; ++$i):
$year = $dateY - $i;
$prop = '';
if($i == $select){
$prop = ' selected';
}
?>
<option value="<?= $year; ?>"<?= $prop; ?>><?= $year; ?></option>
<?php endfor; ?>
</select>
How about this for university graduation (expected) year on recruitment sites, etc.?
<select>
<?php
$dateY = (int) date('Y');
$start = 2; //年後から
$past = 100; //年前まで
$dateY += $start;
for($i = 0; $i < $past; ++$i):
$year = $dateY - $i; ?>
<option value="<?= $year; ?>"><?= $year; ?></option>
<?php endfor; ?>
</select>
Surely, you're not updating this manually every year, are you...?
Mistakes can happen, so let's automate parts that can be automated like this!
As an Amazon Associate, 'Ken' earns from qualifying purchases.
If this was helpful, we appreciate your support!
Any support received will be used for childcare.
Or support us by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
楽天市場
Yahoo!ショッピング
PR