Dynamically generate years in PHP

Sometimes we need to select year value from drop-down and for that we hardcode the year values in HTML option fields. It may me cumbersome at the point when we want to add a new year value to the option field as the year value grows as the time progresses. So it is possible to dynamically generate the year values using PHP and we can use those generated year values in HTML select option tag.

You may also read Dynamically generate months in PHP

Here is the example how we can generate a range of year values in PHP technology.

Here is the output when we run the generate_year file in browser.

generate years php

In the above screen-shot, the default – last 10 years means if we do not pass any parameter’s value then the function generate_years() generates last 10 years including current year; the generate from starting year 1990 to current year means when we pass first parameter(select tag’s id attribute’s value) value as ‘year’ and second parameter value as 1990 then the function generate_years(‘year’, 1990) generates year value from 1990 to 2016; the generate from starting year 1990 to 2030 means when we pass first parameter(select tag’s id attribute’s value) value as ‘year’, second parameter value as 1990 and third parameter value as 2030 then the function generate_years(‘year’, 1990, 2030) generates year value from 1990 to 2030.

Thanks for reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.