Web Design
Web Design Surrey Web Design Services in Surrey

Tutorial Categories

Links & Services

Mailing List

For special offers and annoucements, please enter your email address below.

PHP Dynamically Generated Year Dropdown

In this tutorial I'm going to show you how to create a php function that will decrease the amount of text you have to write to create year dropdowns. If you have used functions in PHP before, it's a great way to get started. The end result should look like this:

In what year were you born?

STEP 1:

First we create the php function file. In this file we create a function called yearDropdown. You can pass 3 variables to this function. The first year of your dropdown, the last year and an id for the dropdown. However, we will create it in such a way that, if you wish, you can omit the id variable. It is really only need when you have more than one year dropdown on your page.

<?php 
function yearDropdown($startYear, $endYear, $id="year"){ 
    //start the select tag 
    echo "<select id=".$id." name=".$id.">n"; 
         
        //echo each year as an option     
        for ($i=$startYear;$i<=$endYear;$i++){ 
        echo "<option value=".$i.">".$i."</option>n";     
        } 
     
    //close the select tag 
    echo "</select>"; 
} 
?>

STEP 2:

Next we need to "include" the function file in your web page and then call the function.

What year were you born in?
<?php  

//call the function 

yearDropdown(1900, 2009);  

?>

OUTPUT:

In what year were you born?

 

ALTERNATIVE STEP 2:

Alternatively, to use the function more than once, include an id variable:

<?php  

//call the function and give it an id 

yearDropdown(1900, 2009, "BirthDate");  



//call the function again and give it a different id 

yearDropdown(1920, 2029, "GraduationDate");  

?>

OUTPUT:


More PHP Tutorials

Recursively Remove Files in Linux

View More...

Output a list of images using PHP

View More...

Output All PHP Session Variables

View More...

Dynamically Generated PHP Bar Graphs

View More...