Front-End & Daily

[PHP] Sample to automatically generate select option tags from the latest year back to the past 100 years

[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!

Comments

After reviewing the content, we will publish it, omitting personal information.

Enter your name and email address too

Please enter if you would like a reply by email.

We will not disclose any personal information provided. It will only be used for replies.

It will be sent directly. Please confirm and click 'Send'.

If this was helpful, we appreciate your support!
Any support received will be used for childcare.

Send support via OFUSE


Or support us by buying something from the buttons below
(You don't have to buy the linked product.)

Amazon

楽天市場

Yahoo!ショッピング

PR

As an Amazon Associate, 'Ken' earns from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark