Snippets › Generate Date of Birth Select inputs Dynamically PHP

  • Published on 6th Sep 2017

There are times when you need to insert date of birth <select> input box in your HTML form. Here's small PHP snippet to dynamically populate the HTML SELECT element with Date of Birth for you. Just copy and use in your projects.

//year
echo '&lt;select name="year"&gt;';
for($i = date('Y'); $i &gt;= date('Y', strtotime('-90 years')); $i--){
  echo "&lt;option value=\"$i\"&gt;$i&lt;/option&gt;";
} 
echo '&lt;/select&gt;';

//month
echo '&lt;select name="month"&gt;';
for($i = 1; $i &lt;= 12; $i++){
    $dt = DateTime::createFromFormat('!m', $i);
    echo "&lt;option value=\"$i\"&gt;".$dt-&gt;format('F')."&lt;/option&gt;";
}
echo '&lt;/select&gt;';

//date
echo '&lt;select name="day"&gt;';
for($i = 1; $i &lt;= 31; $i++){
    echo "&lt;option value=\"$i\"&gt;$i&lt;/option&gt;";
}   
echo '&lt;/select&gt;';