Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat array to a certain length?

Tags:

arrays

php

repeat

I'm having an array for example with 4 elements array("a", "b", "c", d"); what is the fastest way to repeat this array to create a new array with a certain length, e.g 71 elements?

like image 971
Teiv Avatar asked Aug 29 '10 16:08

Teiv


Video Answer


3 Answers

Solution using SPL InfiniteIterator:

<?php
function 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...

like image 36
NikiC Avatar answered Sep 17 '22 12:09

NikiC


// 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 array
while(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);
like image 120
2ndkauboy Avatar answered Sep 19 '22 12:09

2ndkauboy


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
like image 26
Frxstrem Avatar answered Sep 18 '22 12:09

Frxstrem