Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to fill an array with keys and values so 1 = 1, 2 = 2, 3 = 3 etc

Tags:

arrays

php

I am looking to do something like (psuedo_code)

$myarray = fill_array_keys_and_values_from_parameter1_until_parameter2(18, 50);

So that I get

$myarray= array(

'18' => '18',
'19' => '19',
...
'50' => '50'
)

without having to a for loop ideally. Is there such a PHP function, I had a browse of the manual but could not see what I was looking for.

Thanks in advance

like image 614
Mazatec Avatar asked Dec 15 '10 18:12

Mazatec


People also ask

How do you fill an array with arrays?

Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


2 Answers

I don't think there is a specific function that can do this (although there are a couple that come close.)

What about doing this?

$values = range(18, 50);
$array = array_combine($values, $values);
like image 127
simshaun Avatar answered Sep 28 '22 12:09

simshaun


Using a for loop:

$arr = array();
foreach (range(18, 50) as $i) {
    $arr[$i] = $i;
}

simshaun's solution is much better, though.

like image 43
Rafe Kettler Avatar answered Sep 28 '22 12:09

Rafe Kettler