PHP 'Years' array PHP 'Years' array arrays arrays

PHP 'Years' array


Not sure why you're using the session for this, but generating the array can be done with the array_combine function.

$years = array_combine(range(date("Y"), 1910), range(date("Y"), 1910));

Reversing the parameters to range will give you a descending array and array_combine will use the first array as the keys and the second as the values, giving the array(1910 => 1910, ...); map you're after.


reverse the numbers in the range to get years in descending order

$years = range(2010, 1900); // => [2010, 2009, 2008, ... ]

use date('Y') instead of hard-coding the current year

$years = range(date('Y'), 1900);

append an option "Select year" at the beginning

array_unshift($years, "Select year");

And finally why have a select drop-down for year or date of birth at all? It might be prevalent but it's super irritating. A simple text-box with validations, something like dd/mm/yyyy or mm/dd/yyyy is way better. Having drop-downs for date, month, and year only means that a user is allowed to select valid values and not necessarily correct values if they find it convoluted just to input a date. Moreover, since users can still enter junk values by modifying the DOM, validations need to be done on the server side. If validations are being done on the server-side, might as well just offer them a simple text box.

Also drop-downs make client-side coding complex. For example, if Feb and a leap year are selected, then a days dropdown should contain 29 days, otherwise 28.


Why do you need to store the array into the session?

Based on your use case, you do not need to use the array to store data beforehand.

define('DOB_YEAR_START', 1900);$current_year = date('Y');for ($count = $current_year; $count >= DOB_YEAR_START; $count--){    print "<option value='{$count}'>{$count}</option>";}