Borislav Stankov Borislav Stankov - 3 months ago 6
PHP Question

How to get all posible chunks of array with php?

I have an array for example

2,3,4,10,20,30,102


I need all possible 3 consecutive elements array like below:

2,3,4
3,4,10
4,10,20
10,20,30
20,30,102

Answer
    $arr= array(2,3,4,10,20,30,102);
    $arr2=$arr;
    $arr3=array();    
    while(count($arr2)>=3)
    {
        $array= array_chunk($arr2, 3);
        if(count($array)>0)
        {
            array_push($arr3, $array[0]);
            array_shift($arr2);
        }
    }   
    var_dump($arr3);

$arr3 is what you want.