HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Dynamic array of Years

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayyearsdynamic

Problem

I wanted to make a dynamic select statement from this year to 10 years. This gets the job done, but I feel like it's a little much.

form_dropdown('year', array_combine(range(date('Y'), date('Y')+10), range(date('Y'), date('Y')+10)), set_value('year'));


Specifically, is there a better way to create this array, other than this?

array_combine(range(date('Y'), date('Y')+10), range(date('Y'), date('Y')+10))


Desired output (at least for this year):

Array
(
    [2014] => 2014
    [2015] => 2015
    [2016] => 2016
    [2017] => 2017
    [2018] => 2018
    [2019] => 2019
    [2020] => 2020
    [2021] => 2021
    [2022] => 2022
    [2023] => 2023
    [2024] => 2024
)

Solution

In order to get the output that you wanted, using array_combine will most likely be your best bet. You can simplify your statements pretty easily because variables are you friends:

$current_year = date('Y');
$date_range = range($current_year, $current_year+10);

form_dropdown('year', array_combine($date_range, $date_range), set_value('year'));


Addendum by @brettsantore

I think this solves what I thought to be a problem, the combining of so many functions. I ended up simplifying it a little more.

$current_year = date('Y');
$range = range($current_year, $current_year+10);
$years = array_combine($range, $range);

Code Snippets

$current_year = date('Y');
$date_range = range($current_year, $current_year+10);

form_dropdown('year', array_combine($date_range, $date_range), set_value('year'));
$current_year = date('Y');
$range = range($current_year, $current_year+10);
$years = array_combine($range, $range);

Context

StackExchange Code Review Q#55806, answer score: 4

Revisions (0)

No revisions yet.