1

I have a range of 67 numbers, something 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

Cœur
  • 37,241
  • 25
  • 195
  • 267
smith
  • 11
  • 1
  • By *it doesnt matter what the values are* you mean "they do already exist but are not important for the question" or "they do not exist and you dont care what they will be"? In other words, is this about merging a subset of an array into another or is it about padding an array with keys? – Gordon Feb 26 '10 at 12:22

4 Answers4

3

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.

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
1

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

ghostdog74
  • 327,991
  • 56
  • 259
  • 343
0

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);

?>
codaddict
  • 445,704
  • 82
  • 492
  • 529
0

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

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

}
streetparade
  • 32,000
  • 37
  • 101
  • 123