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?
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...
// 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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With