Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a Select Box with Years using PHP [closed]

Tags:

php

I would like to fill a select box with year starting from 1950 to the current year. How can I achieve this using PHP? I would not like to use JavaScript for this.

<select><?php
     $currentYear = date('Y');
        foreach (range(1950, $currentYear) as $value) {
            echo "< option>" . $value . "</option > ";

        }
?>
</select>
like image 363
Abishek Avatar asked Aug 16 '11 18:08

Abishek


3 Answers

Use range to create an array containing all the required years, loop that array and print an option for each of the values.

You can use date('Y') to figure out the current year.

// use this to set an option as selected (ie you are pulling existing values out of the database)
$already_selected_value = 1984;
$earliest_year = 1950;

print '<select name="some_field">';
foreach (range(date('Y'), $earliest_year) as $x) {
    print '<option value="'.$x.'"'.($x === $already_selected_value ? ' selected="selected"' : '').'>'.$x.'</option>';
}
print '</select>';

Try it here: http://codepad.viper-7.com/Pw3U4O

Documentation

  • foreach - http://php.net/manual/en/control-structures.foreach.php
  • range - http://php.net/manual/en/function.range.php
  • date - http://php.net/manual/en/function.date.php
like image 146
Chris Baker Avatar answered Oct 15 '22 19:10

Chris Baker


<select name="select">
<?php 
   for($i = 1950 ; $i < date('Y'); $i++){
      echo "<option>$i</option>";
   }
?>
</select>

Something like this?

like image 15
sn0ep Avatar answered Oct 15 '22 18:10

sn0ep


<?php

$starting_year  = 1950;
$ending_year    = 2011;

for($starting_year; $starting_year <= $ending_year; $starting_year++) {
    $years[] = '<option value="'.$starting_year.'">'.$starting_year.'</option>';
}

?>

<select>
    <?php echo implode("\n\r", $years);  ?>
</select> 

Option #2:

<select>
<?php

foreach(range(1950, (int)date("Y")) as $year) {
    echo "\t<option value='".$year."'>".$year."</option>\n\r";
}

?>
</select>
like image 4
Phill Pafford Avatar answered Oct 15 '22 18:10

Phill Pafford