2

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.

4

3 Answers 3

6

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
        )

)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks!! This works. How can i access individual element of the result_arr?
Thats the simplest thing that you need to do over here
you can access it value with echo $result_arr[0][0]; and so on.
Yeah figured it out. Thanks
2
<?php

$input      = range(1,11);
$chunk_size = 3;
$output     = array_chunk($input, $chunk_size);

// If we can't chunk into equal sized parts merge the last two arrays.
if(count($input) % $chunk_size) {
    $leftovers = array_pop($output);
    $last      = array_pop($output);
    array_push($output, array_merge($last, $leftovers));
}

var_export($output);

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,
    4 => 11,
  ),
)

Comments

0

Here you go

function SplitLike($array, $groups)
{
   $result = [];
   $left = count($array);
   foreach ($groups as $i => $group) {
       $result[$i] = array_slice($array, count($array) - $left, $group);
       $left -= $group;
   }
   return $result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.