views:

50

answers:

5

I want to know if it is possible to take an array and insert the array's values into a bigger array, multiple times, so that the values of the smaller array fill up the bigger array.

Say array1 has values ([0 => 'a'],[1 => 'b'],[2 => 'c']), and array2 can hold 8 values. So, how would I take the values of array1 and insert them into array2 continuously until array2 runs out of space, so that array2 would have the values 'a','b','c','a','b','c','a','b'?

Thanks in advance, ~Hussain~

A: 

Essentially, you want to loop over and over the small array, adding each element to the new array until it has reached the desired size.

Consider this:

$max = 8;

$Orig_Array = array('a', 'b', 'c');
$Next_Array = array();

while True
{
    foreach($Orig_Array as $v)
    {
       $Next_Array[] = $v;
       if(count($Next_Array) >= $max)
          break 2;
    }
}
gahooa
A: 

Assuming that your input array is indexed sequentially:

$len = count($input);
$output = array();
for ($i = 0; $i < MAX_SIZE; ++$i) 
  $output[] = $input[$i % $len];
Victor Nicollet
A: 

Try this:

$array1 = array('a', 'b', 'c');
$array2 = array();

function insert_array(&$source, &$dest, $n) {
    for ($x = 0; $x < $n; ++$x) {
     $key = $x % count($source);
     $dest[$x] = $source[$key];
    }
}

insert_array($array1, $array2, 8);
Sbm007
A: 
$a = array('a','b','c');
$desired = 8;

$b = array();
for($i=0;$i<($desired/count($a))+1;++$i) $b = array_merge($b,$a);
array_splice($b,$desired);

Or

$a = array('a','b','c');
$desired = 8;

$b = array();
for($i=0;$i<$desired/count($a);++$i) $b = array_merge($b,$a);
for($i=0;$i<($desired-count($b)-1);++$i) $b[] = $a[$i];

The first one fills up an array so that it has at least desired number of elements and cuts off the rest. The second one fills up an array up the desired number of elements modulo original array size and adds up the rest.

Michael Krelin - hacker
A: 

Here's one using the input array's internal pointer, to keep things conceptually simple:

$input = array(1, 2, 3);
$size = 32;

$output = array();
for ( $i = 0; $i < $size; $i++ ) {
  $curr = current($input);
  if ( $curr === false ) {
    reset($input);
    $curr = current($input);
  }
  $output[] = $curr;
  next($input);
}

print_r($output);die;
Derek Illchuk