开发者

iterate through range of numbers to add as keys

I have a range of 67 numbers, someth开发者_开发技巧ing like 256 through to 323, which I want to add to an existing array. it doesn't matter what the values are.

looking for code to iterate through those numbers to add them as keys to the array without adding each one at a time


Try array_fill_keys and range

$existingArray =  array('foo', 'bar', 'baz');
$existingArray += array_fill_keys(range(256,323), null);

Use whatever you like instead of null. You could also use array_flip() instead of array_fill_keys(). You'd get the index keys as values then, e.g. 256 => 1, 257 => 2, etc.

Alternatively, use array_merge instead of the + operator. Depends on the outcome you want.


you can use range() eg range(256,323)


push(); could be a look worth, or you can do it like this

for($i=0;$i<count($array);$i++)
{
$anotherArray[$i] = $array[$i];

}


You can try using the range and array_merge functions.

Something like:

<?php

$arr = array(1,2,3); // existing array.
$new_ele = range(256,323); 

// add the new elements to the array.
$arr= array_merge($arr,$new_ele); 

var_dump($arr);

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜