Search code examples
phparrayssplit

Split flat array into multiple arrays with specific counts dictated by another array of integers


I have an array of dynamic length L1. I need to split this array into L2 number of arrays each having LEN[i] numbers from the original array.

Input arrays:

$array = [1,2,3,4,5,6,7,8,9,10]
    
$LEN = [3,3,4]

$LEN states how many elements each new array should contain. The 3 arrays will be:

$a1 = [1,2,3]

$a2 = [4,5,6]

$a3 = [7,8,9,10]

I have tried a lot of ways but nothing seems to be working. Any help would be greatly appreciated.


Solution

  • If you need such a variable array length of chunks then you can create your own functionality using simple foreach and array_splice like as

    $array=[1,2,3,4,5,6,7,8,9,10];
    
    $arr = [3,3,4];
    $result_arr = [];
    foreach($arr as $k => $v){
        $result_arr[$k] = array_splice($array,0,$v);
    }
    print_R($result_arr);
    

    Output:

    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )
    
        [1] => Array
            (
                [0] => 4
                [1] => 5
                [2] => 6
            )
    
        [2] => Array
            (
                [0] => 7
                [1] => 8
                [2] => 9
                [3] => 10
            )
    
    )