I'm having a small issue in php and i know the solution is straightforward but i can't seem to get around to it.
basically i have an array and i need small slices of it until the end.
<?php
$main = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$start = 5;
$sliced = array_slice($main, $start);
$offset=3;
$startx = $start;
foreach($sliced as $s)
{
$start_pt = $startx-$offset;
$end_pt = ($startx) - count($main);
$sli = array_slice($main,$start_pt,$end_pt+1);
print_r($sli);
echo "<br>##############################<br>";
$startx++;
}
The above kinda works except for the last array which return blank since the length is now -1 or -0. It's taking it as length instead of offset.
Any easier/better way to do the above?
Result :
Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 6 )
##############################
Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 7 )
##############################
Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 )
##############################
Array ( [0] => 6 [1] => 7 [2] => 8 [3] => 9 )
##############################
Array ( [0] => 7 [1] => 8 [2] => 9 [3] => 10 )
##############################
Array ( [0] => 8 [1] => 9 [2] => 10 [3] => 11 )
##############################
Array ( [0] => 9 [1] => 10 [2] => 11 [3] => 12 )
##############################
Array ( [0] => 10 [1] => 11 [2] => 12 [3] => 13 )
##############################
Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 )
##############################
Array ( )
##############################
I think your purpose is to make overlapping ranges of same length from your array so you can try this:
and this will print
It works with both ordered and associative arrays
What you want to do you can easily do with array_slice() and array_chunk()
first you need to slice array for offset and then split into chunks
So what it does it loops through array which was sliced for your first offset then it counts how many times it should iterate size of an array / size of a chunk and on each iteration adds the size of chunk. Inside the loop it actually makes chunk and prints it.
Output: