How to generate an array of years dynamically containing the index as the year and the value as the year itself?

3

I have a routine that generates a list of years dynamically from an initial year defined in the array which in this case is the year 2015 up to the current year.

View array structure:

$rray = array(
            "1" => "2015" #Ano inicial
        );

Routine that generates list of years:

<?php
$rray = array(
            "1" => "2015"
        );

$ano = $rray[1];
$i = 1;

while ($ano <= date("Y")) {
    $rray[$i] = $ano;
    $ano++;
    $i++;
}

print_r($rray);

The above routine generates the following output array:

Array
(
    [1] => 2015
    [2] => 2016
    [3] => 2017
)

But I would like indexes that are numeric [1] [2] [3] to be the year itself.

Instead of being

Array
(
    [1] => 2015
    [2] => 2016
    [3] => 2017
)

I would like it to be

Array
(
    [2015] => 2015
    [2016] => 2016
    [2017] => 2017
)

In what way could I do this?

    
asked by anonymous 02.02.2017 / 19:58

2 answers

4

You can use range() to generate the list of years and array_combine() to transform the value of $keys into the keys themselves:

$keys = range(2015, 2020);
$arr = array_combine($keys , $keys);

Or:

$year = date('Y');
$keys = range($year, $year + 10);
$arr = array_combine($keys , $keys);

Output:

Array
(
    [2015] => 2015
    [2016] => 2016
    [2017] => 2017
    [2018] => 2018
    [2019] => 2019
    [2020] => 2020
)
    
02.02.2017 / 20:03
2

You can do that too, very simple.

Code:

<?php

$rray = array();
$ano = '2015';

while ($ano <= date('Y')) {
    $rray[$ano] = $ano;
    $ano++;
}

print_r($rray);

?>

Output:

Array
(
    [2015] => 2015
    [2016] => 2016
    [2017] => 2017
)
    
02.02.2017 / 20:11