1

Is there a neat way to split an array into chunks based on an array of lengths?

Input:

$start = range(0, 30);
$length = [3, 7, 2, 12, 6];

Desired Output:

[
    [0, 1, 2],  // 3
    [4, 5, 6, 7, 8, 9, 10],  // 7
    [11, 12],  // 2
    [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],  // 12
    [25, 26, 27, 28, 29, 30],  // 6
];
1

2 Answers 2

6

Using array_splice:

$target = array(); // or use []  in PHP 5.4
foreach($length as $i) {
    $target[] = array_splice($start, 0, $i);
}

Try it.

Be advised, this changes $start!

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

Comments

2

This is very easily accomplished with the following:

Code:

$target = array();
$offset = 0;

foreach ($length as $lengthValue) {
    $target[] = array_slice($start, $offset, $lengthValue);
    $offset += $lengthValue;
}
var_dump($target);

Explanation:

What you are doing here is using the array_slice() method (very similar to the substr) to extract the portion of the array and then inserting it into the target array. Incrementing the offset each time allows the function to remember which one to use next time.

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.