Setting default year in a selection box


#1

I am new to PHP. I have a selection box with a range of years starting at current year - 5 (2014) through the year 2050. My selection box contains the correct years but I need it to default to the current year. Right now, it defaults to 2014. I’ve been working on this for hours. I thought the $current_year variable was needed in the loop in some way - in order to set the default - but that doesn’t work. After researching and seeing various examples, I’m now thinking I need to build an if statement within the loop but I really don’t know. Help is appreciated.

<form id=“calendarForm” name=“calendarForm” method=“post” action="">
<label for=“select_year”>Select the year: </label>
<select id=“select_year” name=“select_year”>
<?php
$date = new DateTime();
// Sets the current year
$current_year = $date->format(‘Y’);
// Year to start available options.
$earliest_year = ($current_year - 5);
$year = $earliest_year;

for ($year = $earliest_year; $year <= LATEST_YEAR; $year++) {
echo “<option value=’$year’>$year</option>”;
}
?>

</select>


#2

I think I have the solution. I can’t delete my post. Just wanted to stop someone before they put time into helping me.


#3

I already gave you the EXACT working code to do this the other day in your other thread. Why are you posting asking for this?


#4

Honestly, I thought I had posted that question on stackoverflow. I’ve been a bit overwhelmed, seeking help from multiple sites. I just viewed my other posts and your response. You helped and I did make some progress because of it but I couldn’t use “range” and there was something else my professor didn’t like. I’m limited to just the examples he’s given in class. Makes it difficult to even ask for help. Everyone has a better way to do it and my professor won’t approve of 80% of it. It’s all good now. For what it’s worth - like I mentioned above - I tried to delete the post.