I want to drop list of the year starting from the current year to 8 more years but it is listing them. I cannot select the year from drop-down because all of them are listed. I want them to drop down so I can select which one I want from the list.
<?php
class BirthYear
{
public function year(){
$years = array(date("Y"));
foreach($years as $year){
for($i=0; $i < 8; $i++){
$y = $year++;
echo $y."<br>";
}
}
}
}
$y = new BirthYear();
//echo $y->year();
?>
<html>
<style>
label {
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
</style>
<select name="birthYear" id="birthYear-select">
<option value="">Please choose an option</option>
<option value=""><?php echo $y->year();?></option>
</select>
</html>
Here you go! the year() function now returns the year from the current one till the next 8 yeas. you weren’t looping through the array, and you weren’t even returning anything for the year() which caused it to be null.
<?php
class BirthYear
{
public function year()
{
$current_year = date("Y");
$target_year = $current_year + 8;
$years = array();
do {
array_push($years, $current_year);
$current_year++;
} while ($target_year >= $current_year);
return $years;
}
}
$y = new BirthYear();
$years = $y->year();
?>
<select name="birthYear" id="birthYear-select">
<option value="">Please choose an option</option>
<?php foreach ($years as $year) { ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php } ?>
</select>
Answer:
Use something like this:
<?php
class BirthYear
{
public function year(){
$y = array();
$year = date("Y");
for($i=0; $i < 8; $i++){
$y[] = $year++;
}
return $y;
}
}
$y = new BirthYear();
?>
<html>
<style>
label {
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
</style>
<select name="birthYear" id="birthYear-select">
<option value="">Please choose an option</option>
<?php foreach($y->year() as $year) {
echo "<option value=\"$year\">$year</option>\n";
}
?>
</select>
</html>
http://sandbox.onlinephpfunctions.com/code/9042c9b444bcc8281f9ef5de313513823477817f