Repeat array to a certain length? Repeat array to a certain length? arrays arrays

Repeat array to a certain length?


// the variables$array = array("a", "b", "c", "d");$desiredLength = 71;$newArray = array();// create a new array with AT LEAST the desired number of elements by joining the array at the end of the new arraywhile(count($newArray) <= $desiredLength){    $newArray = array_merge($newArray, $array);}// reduce the new array to the desired length (as there might be too many elements in the new array$array = array_slice($newArray, 0, $desiredLength);


Solution using SPL InfiniteIterator:

<?phpfunction fillArray1($length, $values) {    foreach (new InfiniteIterator(new ArrayIterator($values)) as $element) {        if (!$length--) return $result;        $result[] = $element;    }    return $result;}var_dump(fillArray(71, array('a', 'b', 'c', 'd')));

The real SPL hackers might have dropped the if (!$length--) break; and instead used a limit iterator: new LimitIterator(new InfiniteIterator(new ArrayIterator($values)), 0, $length), but I thought that to be overkill...


A simple solution using each() and reset() and the array's internal pointer:

<?php$array = array('a', 'b', 'c', 'd');$length = 71;$result = array();while(count($result) < $length){  $current = each($array);  if($current == false)  {    reset($array);    continue;  }  $result[] = $current[1];}echo count($result); // Output: 71