Search code examples
phparraysloopsarray-push

Insert element into array with specific position in loop


I want to create list of years in array like this:

array
(
'2011' => '2011',
'2010' => '2010',
'2009' => '2009',
...
...
'1905' => '1905'
)

I try to create this array with loop method like this:

$years = array();
for($i=2011;$i>1904;$i--){
  array_push($years,$i);
}

But creates an array like this:

array
(
'0' => '2011',
'1' => '2010',
'2' => '2009',
...
...
'106' => '1905'
)

My question is how can I insert element into array with specific position?
I also look throw relevant question, but couldn't find solution.
Thanks in advance.


Solution

  • You don't need a loop:

    $years = array_combine(range(2011,1905),range(2011,1905));
    

    though I wonder why you need key and value to be identical in your array