note 109797 deleted from ref.array by levim
| From: | levim@php.net | Date: | Tue, 06 May 2014 22:07:20 +0000 |
| Subject: | note 109797 deleted from ref.array by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199461@lists.php.net to get a copy of this message | ||
Note Submitter: q*bist
----
Fill an array with items from another array, wrapping
<?php
function array_window(array $array, $window = 1) {
//return array of size $window filled with elements from $array.
// if count($array) is smaller than $window,
// elements will be repeated in the returned array
$count = count($array);
if ($count >= $window) {
$ret = array_slice($array, 0, $window);
} else {
//wraparound
$ret = array();
for ($i = 0; $i < $window; ++$i) {
$crsr = $i;
if ($crsr >= count($array)) {
$crsr = $crsr - count($array);
}
$ret[] = $array[$crsr];
}
}
return $ret;
}
?>
Usage:
<?php
$test = array('one', 'two', 'three', 'four',
'five', 'six');
print_r(array_window($test, 4));
?>
will print
Array ( [0] => one [1] => two [2] => three [3] => four )
<?php
$test = array('one', 'two', 'three', 'four',
'five', 'six');
print_r(array_window($test, 9));
?>
will print
Array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six [6]
=> one [7] => two [8] => three )