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

Asked

Viewed 354 times

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 to the current year.

See the array structure:

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

Routine that generates the 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
)

However I would like the indexes that are numerical [1] [2] [3] were the same year.

Instead of being

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

I wish it were

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

How could I do that?

2 answers

4


Can use range() to generate the list of years and array_combine() to transform the value of $keys in the keys themselves:

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

Or else:

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

Exit:

Array
(
    [2015] => 2015
    [2016] => 2016
    [2017] => 2017
    [2018] => 2018
    [2019] => 2019
    [2020] => 2020
)

2

You can make it that way too, very simple.

Code:

<?php

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

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

print_r($rray);

?>

Exit:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.